tripal_core.api.inc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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. require_once "tripal_core.schema.api.inc";
  22. // just a temporary function for debugging
  23. function tripal_core_chado_insert_test(){
  24. $ivalues = array(
  25. 'organism_id' => array(
  26. 'genus' => 'Lens',
  27. 'species' => 'culinaris',
  28. ),
  29. 'name' => 'orange1.1g000034m.g',
  30. 'uniquename' => 'orange1.1g000034m.g9',
  31. 'type_id' => array (
  32. 'cv_id' => array (
  33. 'name' => 'sequence',
  34. ),
  35. 'name' => 'gene',
  36. 'is_obsolete' => 0
  37. ),
  38. );
  39. $umatch = array(
  40. 'organism_id' => array(
  41. 'genus' => 'Lens',
  42. 'species' => 'culinaris',
  43. ),
  44. 'uniquename' => 'orange1.1g000034m.g9',
  45. 'type_id' => array (
  46. 'cv_id' => array (
  47. 'name' => 'sequence',
  48. ),
  49. 'name' => 'gene',
  50. 'is_obsolete' => 0
  51. ),
  52. );
  53. $uvalues = array(
  54. 'name' => 'orange1.1g000034m.g',
  55. 'type_id' => array (
  56. 'cv_id' => array (
  57. 'name' => 'sequence',
  58. ),
  59. 'name' => 'mRNA',
  60. 'is_obsolete' => 0
  61. ),
  62. );
  63. $select_multiple = array(
  64. 'dbxref_id' => array(
  65. 'db_id' => 2,
  66. )
  67. );
  68. //$result = tripal_core_chado_insert('feature',$ivalues);
  69. //return "$result->feature_id";
  70. $result = tripal_core_chado_update('feature',$umatch,$uvalues);
  71. //$result = tripal_core_chado_select('feature',array('type_id', 'uniquename'),$select_multiple);
  72. return $result;
  73. }
  74. /**
  75. * Provides a generic routine for inserting into any Chado table
  76. *
  77. * Use this function to insert a record into any Chado table. The first
  78. * argument specifies the table for inserting and the second is an array
  79. * of values to be inserted. The array is mutli-dimensional such that
  80. * foreign key lookup values can be specified.
  81. *
  82. * @param $table
  83. * The name of the chado table for inserting
  84. * @param $values
  85. * An associative array containing the values for inserting.
  86. *
  87. * @return
  88. * On success this function returns TRUE. On failure, it returns FALSE.
  89. *
  90. * Example usage:
  91. * @code
  92. * $values = array(
  93. * 'organism_id' => array(
  94. * 'genus' => 'Citrus',
  95. * 'species' => 'sinensis',
  96. * ),
  97. * 'name' => 'orange1.1g000034m.g',
  98. * 'uniquename' => 'orange1.1g000034m.g',
  99. * 'type_id' => array (
  100. * 'cv_id' => array (
  101. * 'name' => 'sequence',
  102. * ),
  103. * 'name' => 'gene',
  104. * 'is_obsolete' => 0
  105. * ),
  106. * );
  107. * $result = tripal_core_chado_insert('feature',$values);
  108. * @endcode
  109. * The above code inserts a record into the feature table. The $values array is
  110. * nested such that the organism is selected by way of the organism_id foreign
  111. * key constraint by specifying the genus and species. The cvterm is also
  112. * specified using its foreign key and the cv_id for the cvterm is nested as
  113. * well.
  114. *
  115. * @ingroup tripal_api
  116. */
  117. function tripal_core_chado_insert($table,$values){
  118. $insert_values = array();
  119. // get the table description
  120. $table_desc = module_invoke_all('chado_'.$table.'_schema');
  121. // iterate through the values array and create a new 'insert_values' array
  122. // that has all the values needed for insert with all foreign relationsihps
  123. // resolved.
  124. foreach($values as $field => $value){
  125. if(is_array($value)){
  126. // select the value from the foreign key relationship for this value
  127. $results = tripal_core_chado_get_foreign_key($table_desc,$field,$value);
  128. if (sizeof($results) > 1) {
  129. 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);
  130. } elseif (sizeof($results) < 1) {
  131. 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);
  132. } else {
  133. $insert_values[$field] = $results[0];
  134. }
  135. }
  136. else {
  137. $insert_values[$field] = $value;
  138. }
  139. }
  140. // check for violation of any unique constraints
  141. $ukeys = $table_desc['unique keys'];
  142. $ukselect_cols = array();
  143. $ukselect_vals = array();
  144. foreach($ukeys as $name => $fields){
  145. foreach($fields as $index => $field){
  146. // build the arrays for performing a select that will check the contraint
  147. array_push($ukselect_cols,$field);
  148. $ukselect_vals[$field] = $insert_values[$field];
  149. }
  150. // now check the constraint
  151. if(tripal_core_chado_select($table,$ukselect_cols,$ukselect_vals)){
  152. watchdog('tripal_core',"tripal_core_chado_insert: Cannot insert duplicate record into $table table: " . print_r($values,1),array(),'WATCHDOG_ERROR');
  153. return false;
  154. }
  155. }
  156. // if trying to insert a field that is the primary key, make sure it also is unique
  157. $pkey = $table_desc['primary key'][0];
  158. if($insert_values[$pkey]){
  159. if(tripal_core_chado_select($table,array($pkey),array($pkey => $insert_values[$pkey]))){
  160. watchdog('tripal_core',"tripal_core_chado_insert: Cannot insert duplicate primary key into $table table: " . print_r($values,1),array(),'WATCHDOG_ERROR');
  161. return false;
  162. }
  163. }
  164. // make sure required fields have a value
  165. $fields = $table_desc['fields'];
  166. foreach($fields as $field => $def){
  167. // a field is considered missing if it cannot be null and there is no default
  168. // value for it or it is of type 'serial'
  169. if($def['not null'] == 1 and !array_key_exists($field,$insert_values) and !$def['default'] and strcmp($def['type'],serial)!=0){
  170. watchdog('tripal_core',"tripal_core_chado_insert: Field $table.$field cannot be null: " . print_r($values,1),array(),'WATCHDOG_ERROR');
  171. return false;
  172. }
  173. }
  174. // Now build the insert SQL statement
  175. $ifields = array();
  176. $ivalues = array();
  177. $itypes = array();
  178. foreach ($insert_values as $field => $value){
  179. array_push($ifields,$field);
  180. array_push($ivalues,$value);
  181. if(strcmp($fields[$field]['type'],'serial')==0 or
  182. strcmp($fields[$field]['type'],'int')==0){
  183. array_push($itypes,"%d");
  184. } else {
  185. array_push($itypes,"'%s'");
  186. }
  187. }
  188. $sql = "INSERT INTO {$table} (" . implode(", ",$ifields) . ") VALUES (". implode(", ",$itypes) .")";
  189. // finally perform the insert.
  190. if(db_query($sql,$ivalues)){
  191. return true;
  192. }
  193. else {
  194. watchdog('tripal_core',"tripal_core_chado_insert: Cannot insert record into $table table: " . print_r($values,1),array(),'WATCHDOG_ERROR');
  195. return false;
  196. }
  197. return false;
  198. }
  199. /**
  200. * Provides a generic routine for updating into any Chado table
  201. *
  202. * Use this function to update a record in any Chado table. The first
  203. * argument specifies the table for inserting, the second is an array
  204. * of values to matched for locating the record for updating, and the third
  205. * argument give the values to update. The arrays are mutli-dimensional such
  206. * that foreign key lookup values can be specified.
  207. *
  208. * @param $table
  209. * The name of the chado table for inserting
  210. * @param $match
  211. * An associative array containing the values for locating a record to update.
  212. * @param $values
  213. * An associative array containing the values for updating.
  214. *
  215. * @return
  216. * On success this function returns TRUE. On failure, it returns FALSE.
  217. *
  218. * Example usage:
  219. * @code
  220. $umatch = array(
  221. 'organism_id' => array(
  222. 'genus' => 'Citrus',
  223. 'species' => 'sinensis',
  224. ),
  225. 'uniquename' => 'orange1.1g000034m.g7',
  226. 'type_id' => array (
  227. 'cv_id' => array (
  228. 'name' => 'sequence',
  229. ),
  230. 'name' => 'gene',
  231. 'is_obsolete' => 0
  232. ),
  233. );
  234. $uvalues = array(
  235. 'name' => 'orange1.1g000034m.g',
  236. 'type_id' => array (
  237. 'cv_id' => array (
  238. 'name' => 'sequence',
  239. ),
  240. 'name' => 'mRNA',
  241. 'is_obsolete' => 0
  242. ),
  243. );
  244. * $result = tripal_core_chado_update('feature',$umatch,$uvalues);
  245. * @endcode
  246. * The above code species that a feature with a given uniquename, organism_id,
  247. * and type_id (the unique constraint for the feature table) will be updated.
  248. * The organism_id is specified as a nested array that uses the organism_id
  249. * foreign key constraint to lookup the specified values to find the exact
  250. * organism_id. The same nested struture is also used for specifying the
  251. * values to update. The function will find the record that matches the
  252. * columns specified and update the record with the avlues in the $uvalues array.
  253. *
  254. * @ingroup tripal_api
  255. */
  256. function tripal_core_chado_update($table,$match,$values){
  257. $update_values = array(); // contains the values to be updated
  258. $update_matches = array(); // contains the values for the where clause
  259. // get the table description
  260. $table_desc = module_invoke_all('chado_'.$table.'_schema');
  261. // get the values needed for matching in the SQL statement
  262. foreach ($match as $field => $value){
  263. if(is_array($value)){
  264. $results = tripal_core_chado_get_foreign_key($table_desc,$field,$value);
  265. if (sizeof($results) > 1) {
  266. 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);
  267. } elseif (sizeof($results) < 1) {
  268. 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);
  269. } else {
  270. $update_matches[$field] = $results[0];
  271. }
  272. }
  273. else {
  274. $update_matches[$field] = $value;
  275. }
  276. }
  277. // get the values used for updating
  278. foreach ($values as $field => $value){
  279. if(is_array($value)){
  280. $results = tripal_core_chado_get_foreign_key($table_desc,$field,$value);
  281. if (sizeof($results) > 1) {
  282. 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);
  283. } elseif (sizeof($results) < 1) {
  284. 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);
  285. } else {
  286. $update_values[$field] = $results[0];
  287. }
  288. }
  289. else {
  290. $update_values[$field] = $value;
  291. }
  292. }
  293. // now build the SQL statement
  294. $sql = "UPDATE {$table} SET ";
  295. $fields = $table_desc['fields'];
  296. $uargs = array();
  297. foreach($update_values as $field => $value){
  298. if(strcmp($fields[$field]['type'],'serial')==0 or
  299. strcmp($fields[$field]['type'],'int')==0){
  300. $sql .= " $field = %d, ";
  301. } else {
  302. $sql .= " $field = '%s', ";
  303. }
  304. array_push($uargs,$value);
  305. }
  306. $sql = substr($sql,0,-2); // get rid of the trailing comma & space
  307. $sql .= " WHERE ";
  308. foreach($update_matches as $field => $value){
  309. if(strcmp($fields[$field]['type'],'serial')==0 or
  310. strcmp($fields[$field]['type'],'int')==0){
  311. $sql .= " $field = %d AND ";
  312. } else {
  313. $sql .= " $field = '%s' AND ";
  314. }
  315. array_push($uargs,$value);
  316. }
  317. $sql = substr($sql,0,-4); // get rid of the trailing 'AND'
  318. // finally perform the update. If successful, return the updated record
  319. if(db_query($sql,$uargs)){
  320. return true;
  321. }
  322. else {
  323. watchdog('tripal_core',"Cannot update record in $table table. Match:" . print_r($match,1) . ". Values: ". print_r($values,1),array(),'WATCHDOG_ERROR');
  324. return false;
  325. }
  326. return false;
  327. }
  328. /**
  329. * Provides a generic routine for selecting data from a Chado table
  330. *
  331. * Use this function to perform a simple select from any Chado table.
  332. *
  333. * @param $table
  334. * The name of the chado table for inserting
  335. * @param $columns
  336. * An array of column names
  337. * @param $values
  338. * An associative array containing the values for filtering the results.
  339. * @param $has_record
  340. * Set this argument to 'true' to have this function return a numeric
  341. * value for the number of recrods rather than the array of records. this
  342. * can be useful in 'if' statements to check the presence of particula records.
  343. *
  344. * @return
  345. * A database query result resource, FALSE if the query was not executed
  346. * correctly, or the number of records in the dataset if $has_record is set.
  347. *
  348. * Example usage:
  349. * @code
  350. * $columns = array('feature_id','name');
  351. * $values = array(
  352. * 'organism_id' => array(
  353. * 'genus' => 'Citrus',
  354. * 'species' => 'sinensis',
  355. * ),
  356. * 'uniquename' => 'orange1.1g000034m.g',
  357. * 'type_id' => array (
  358. * 'cv_id' => array (
  359. * 'name' => 'sequence',
  360. * ),
  361. * 'name' => 'gene',
  362. * 'is_obsolete' => 0
  363. * ),
  364. * );
  365. * $result = tripal_core_chado_select('feature',$columns,$values);
  366. * @endcode
  367. * The above code selects a record from the feature table using the three fields
  368. * that uniquely identify a feature. The $columns array simply lists the columns
  369. * to select. The $values array is nested such that the organism is identified by
  370. * way of the organism_id foreign key constraint by specifying the genus and
  371. * species. The cvterm is also specified using its foreign key and the cv_id
  372. * for the cvterm is nested as well.
  373. *
  374. * @ingroup tripal_api
  375. */
  376. function tripal_core_chado_select($table,$columns,$values,$has_record = 0){
  377. // get the table description
  378. $table_desc = module_invoke_all('chado_'.$table.'_schema');
  379. $select = '';
  380. $from = '';
  381. $where = '';
  382. $args = array();
  383. foreach($values as $field => $value){
  384. $select[] = $field;
  385. if(is_array($value)){
  386. // select the value from the foreign key relationship for this value
  387. $results = tripal_core_chado_get_foreign_key($table_desc,$field,$value);
  388. if (sizeof($results) < 1) {
  389. // foreign key records are required
  390. // thus if none matched then return false and alert the admin through watchdog
  391. watchdog('tripal_core',
  392. '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',
  393. array('!table' => $table,
  394. '!columns' => '<pre>' . print_r($columns, TRUE) . '</pre>',
  395. '!values' => '<pre>' . print_r($values, TRUE) . '</pre>',
  396. '!field' => $field,
  397. ),
  398. WATCHDOG_WARNING);
  399. return false;
  400. } elseif (sizeof($results) == 1) {
  401. $where[$field] = $results[0];
  402. } else {
  403. $where[$field] = $results;
  404. }
  405. }
  406. else {
  407. $where[$field] = $value;
  408. }
  409. }
  410. // now build the SQL select statement
  411. if (empty($where)) {
  412. // sometimes want to select everything
  413. $sql = "SELECT " . implode(',',$columns) . " ";
  414. $sql .= "FROM {$table} ";
  415. } else {
  416. $sql = "SELECT " . implode(',',$columns) . " ";
  417. $sql .= "FROM {$table} ";
  418. $sql .= "WHERE ";
  419. foreach($where as $field => $value){
  420. if (is_array($value)) {
  421. $sql .= "$field IN (".db_placeholders($value,'varchar').") AND ";
  422. foreach ($value as $v) { $args[] = $v; }
  423. } else {
  424. $sql .= "$field = '%s' AND ";
  425. $args[] = $value;
  426. }
  427. }
  428. $sql = substr($sql,0,-4); // get rid of the trailing 'AND'
  429. }
  430. $resource = db_query($sql,$args);
  431. $results = array();
  432. while ($r = db_fetch_object($resource)) {
  433. $results[] = $r;
  434. }
  435. if(!$has_record){
  436. return $results;
  437. } else{
  438. return scalar($results);
  439. }
  440. }
  441. /**
  442. * Gets the value of a foreign key relationship
  443. *
  444. * This function is used by tripal_core_chado_select, tripal_core_chado_insert,
  445. * and tripal_core_chado_update to iterate through the associate array of
  446. * values that gets passed to each of those routines. The values array
  447. * is nested where foreign key contraints are used to specify a value that. See
  448. * documentation for any of those functions for further information.
  449. *
  450. * @param $table_desc
  451. * A table description for the table with the foreign key relationship to be identified generated by
  452. * hook_chado_<table name>_schema()
  453. * @param $field
  454. * The field in the table that is the foreign key.
  455. * @param $values
  456. * An associative array containing the values
  457. *
  458. * @return
  459. * A string containg the results of the foreign key lookup, or FALSE if failed.
  460. *
  461. * Example usage:
  462. * @code
  463. *
  464. * $values = array(
  465. * 'genus' => 'Citrus',
  466. * 'species' => 'sinensis',
  467. * );
  468. * $value = tripal_core_chado_get_foreign_key('feature','organism_id',$values);
  469. *
  470. * @endcode
  471. * The above code selects a record from the feature table using the three fields
  472. * that uniquely identify a feature. The $columns array simply lists the columns
  473. * to select. The $values array is nested such that the organism is identified by
  474. * way of the organism_id foreign key constraint by specifying the genus and
  475. * species. The cvterm is also specified using its foreign key and the cv_id
  476. * for the cvterm is nested as well.
  477. *
  478. * @ingroup tripal_api
  479. */
  480. function tripal_core_chado_get_foreign_key($table_desc,$field,$values){
  481. // get the list of foreign keys for this table description and
  482. // iterate through those until we find the one we're looking for
  483. $fkeys = $table_desc['foreign keys'];
  484. if($fkeys){
  485. foreach($fkeys as $name => $def){
  486. if (is_array($def['table'])) {
  487. //foreign key was described 2X
  488. $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")).".";
  489. watchdog('tripal_core', $message);
  490. drupal_set_message($message,'error');
  491. continue;
  492. }
  493. $table = $def['table'];
  494. $columns = $def['columns'];
  495. // iterate through the columns of the foreign key relationship
  496. foreach($columns as $left => $right){
  497. // does the left column in the relationship match our field?
  498. if(strcmp($field,$left)==0){
  499. // the column name of the foreign key matches the field we want
  500. // so this is the right relationship. Now we want to select
  501. $select_cols = array($right);
  502. $result = tripal_core_chado_select($table,$select_cols,$values);
  503. $fields = array();
  504. foreach ($result as $obj) {
  505. $fields[] = $obj->$right;
  506. }
  507. return $fields;
  508. }
  509. }
  510. }
  511. }
  512. else {
  513. // TODO: what do we do if we get to this point and we have a fk
  514. // relationship expected but we don't have any definition for one in the
  515. // table schema??
  516. $message = "There is no foreign key relationship defined for ".$field.". To define a foreign key relationship, determine the table this foreign key referrs to (<foreign table>) and then implement hook_chado_<foreign table>_schema(). See tripal_feature_chado_feature_schema for an example.";
  517. watchdog('tripal_core', $message);
  518. drupal_set_message($message,'error');
  519. }
  520. return false;
  521. }