tripal_core.api.inc 20 KB

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