tripal_core.api.inc 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230
  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_schema_api Tripal Schema API
  23. * @{
  24. * Provides an application programming interface (API) used to describe chado tables to
  25. * drupal/tripal
  26. * @}
  27. * @ingroup tripal_api
  28. */
  29. require_once "tripal_core.schema.api.inc";
  30. // just a temporary function for debugging
  31. function tripal_core_chado_insert_test(){
  32. $ivalues = array(
  33. 'organism_id' => array(
  34. 'genus' => 'Lens',
  35. 'species' => 'culinaris',
  36. ),
  37. 'name' => 'orange1.1g000034m.g',
  38. 'uniquename' => 'orange1.1g000034m.g9',
  39. 'type_id' => array (
  40. 'cv_id' => array (
  41. 'name' => 'sequence',
  42. ),
  43. 'name' => 'gene',
  44. 'is_obsolete' => 0
  45. ),
  46. );
  47. $umatch = array(
  48. 'organism_id' => array(
  49. 'genus' => 'Lens',
  50. 'species' => 'culinaris',
  51. ),
  52. 'uniquename' => 'orange1.1g000034m.g9',
  53. 'type_id' => array (
  54. 'cv_id' => array (
  55. 'name' => 'sequence',
  56. ),
  57. 'name' => 'gene',
  58. 'is_obsolete' => 0
  59. ),
  60. );
  61. $uvalues = array(
  62. 'name' => 'orange1.1g000034m.g',
  63. 'type_id' => array (
  64. 'cv_id' => array (
  65. 'name' => 'sequence',
  66. ),
  67. 'name' => 'mRNA',
  68. 'is_obsolete' => 0
  69. ),
  70. );
  71. $select_multiple = array(
  72. 'dbxref_id' => array(
  73. 'db_id' => 2,
  74. )
  75. );
  76. //$result = tripal_core_chado_insert('feature',$ivalues);
  77. //return "$result->feature_id";
  78. $result = tripal_core_chado_update('feature',$umatch,$uvalues);
  79. //$result = tripal_core_chado_select('feature',array('type_id', 'uniquename'),$select_multiple);
  80. return $result;
  81. }
  82. /**
  83. * Provides a generic routine for inserting into any Chado table
  84. *
  85. * Use this function to insert a record into any Chado table. The first
  86. * argument specifies the table for inserting and the second is an array
  87. * of values to be inserted. The array is mutli-dimensional such that
  88. * foreign key lookup values can be specified.
  89. *
  90. * @param $table
  91. * The name of the chado table for inserting
  92. * @param $values
  93. * An associative array containing the values for inserting.
  94. *
  95. * @return
  96. * On success this function returns TRUE. On failure, it returns FALSE.
  97. *
  98. * Example usage:
  99. * @code
  100. * $values = array(
  101. * 'organism_id' => array(
  102. * 'genus' => 'Citrus',
  103. * 'species' => 'sinensis',
  104. * ),
  105. * 'name' => 'orange1.1g000034m.g',
  106. * 'uniquename' => 'orange1.1g000034m.g',
  107. * 'type_id' => array (
  108. * 'cv_id' => array (
  109. * 'name' => 'sequence',
  110. * ),
  111. * 'name' => 'gene',
  112. * 'is_obsolete' => 0
  113. * ),
  114. * );
  115. * $result = tripal_core_chado_insert('feature',$values);
  116. * @endcode
  117. * The above code inserts a record into the feature table. The $values array is
  118. * nested such that the organism is selected by way of the organism_id foreign
  119. * key constraint by specifying the genus and species. The cvterm is also
  120. * specified using its foreign key and the cv_id for the cvterm is nested as
  121. * well.
  122. *
  123. * @ingroup tripal_api
  124. */
  125. function tripal_core_chado_insert($table,$values){
  126. $insert_values = array();
  127. // get the table description
  128. $table_desc = module_invoke_all('chado_'.$table.'_schema');
  129. // iterate through the values array and create a new 'insert_values' array
  130. // that has all the values needed for insert with all foreign relationsihps
  131. // resolved.
  132. foreach($values as $field => $value){
  133. if(is_array($value)){
  134. // select the value from the foreign key relationship for this value
  135. $results = tripal_core_chado_get_foreign_key($table_desc,$field,$value);
  136. if (sizeof($results) > 1) {
  137. 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);
  138. } elseif (sizeof($results) < 1) {
  139. 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);
  140. } else {
  141. $insert_values[$field] = $results[0];
  142. }
  143. }
  144. else {
  145. $insert_values[$field] = $value;
  146. }
  147. }
  148. // check for violation of any unique constraints
  149. $ukeys = $table_desc['unique keys'];
  150. $ukselect_cols = array();
  151. $ukselect_vals = array();
  152. if ($ukeys) {
  153. foreach($ukeys as $name => $fields){
  154. foreach($fields as $index => $field){
  155. // build the arrays for performing a select that will check the contraint
  156. array_push($ukselect_cols,$field);
  157. $ukselect_vals[$field] = $insert_values[$field];
  158. }
  159. // now check the constraint
  160. if(tripal_core_chado_select($table,$ukselect_cols,$ukselect_vals)){
  161. watchdog('tripal_core',"tripal_core_chado_insert: Cannot insert duplicate record into $table table: " . print_r($values,1),array(),'WATCHDOG_ERROR');
  162. return false;
  163. }
  164. }
  165. }
  166. // if trying to insert a field that is the primary key, make sure it also is unique
  167. $pkey = $table_desc['primary key'][0];
  168. if($insert_values[$pkey]){
  169. if(tripal_core_chado_select($table,array($pkey),array($pkey => $insert_values[$pkey]))){
  170. watchdog('tripal_core',"tripal_core_chado_insert: Cannot insert duplicate primary key into $table table: " . print_r($values,1),array(),'WATCHDOG_ERROR');
  171. return false;
  172. }
  173. }
  174. // make sure required fields have a value
  175. $fields = $table_desc['fields'];
  176. foreach($fields as $field => $def){
  177. // a field is considered missing if it cannot be null and there is no default
  178. // value for it or it is of type 'serial'
  179. if($def['not null'] == 1 and !array_key_exists($field,$insert_values) and !isset($def['default']) and strcmp($def['type'],serial)!=0){
  180. watchdog('tripal_core',"tripal_core_chado_insert: Field $table.$field cannot be null: " . print_r($values,1),array(),'WATCHDOG_ERROR');
  181. return false;
  182. }
  183. }
  184. // Now build the insert SQL statement
  185. $ifields = array();
  186. $ivalues = array();
  187. $itypes = array();
  188. foreach ($insert_values as $field => $value){
  189. array_push($ifields,$field);
  190. array_push($ivalues,$value);
  191. if(strcmp($fields[$field]['type'],'serial')==0 or
  192. strcmp($fields[$field]['type'],'int')==0){
  193. array_push($itypes,"%d");
  194. } else {
  195. array_push($itypes,"'%s'");
  196. }
  197. }
  198. $sql = "INSERT INTO {$table} (" . implode(", ",$ifields) . ") VALUES (". implode(", ",$itypes) .")";
  199. // finally perform the insert.
  200. $previous_db = tripal_db_set_active('chado'); // use chado database
  201. $result = db_query($sql,$ivalues);
  202. tripal_db_set_active($previous_db); // now use drupal database
  203. if($result){
  204. // add primary keys to values before return
  205. $primary_key = array();
  206. foreach ($table_desc['primary key'] as $field) {
  207. $value = db_last_insert_id($table, $field);
  208. $values[$field] = $value;
  209. }
  210. return $values;
  211. }
  212. else {
  213. watchdog('tripal_core',"tripal_core_chado_insert: Cannot insert record into $table table: " . print_r($values,1),array(),'WATCHDOG_ERROR');
  214. return false;
  215. }
  216. return false;
  217. }
  218. /**
  219. *
  220. */
  221. function tripal_core_chado_delete($table,$match){
  222. $delete_matches = array(); // contains the values for the where clause
  223. // get the table description
  224. $table_desc = module_invoke_all('chado_'.$table.'_schema');
  225. // get the values needed for matching in the SQL statement
  226. foreach ($match as $field => $value){
  227. if(is_array($value)){
  228. $results = tripal_core_chado_get_foreign_key($table_desc,$field,$value);
  229. if (sizeof($results) > 1) {
  230. 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);
  231. } elseif (sizeof($results) < 1) {
  232. 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);
  233. } else {
  234. $delete_matches[$field] = $results[0];
  235. }
  236. }
  237. else {
  238. $delete_matches[$field] = $value;
  239. }
  240. }
  241. // now build the SQL statement
  242. $sql = "DELETE FROM {$table} WHERE ";
  243. $dargs = array();
  244. foreach($delete_matches as $field => $value){
  245. if(strcmp($fields[$field]['type'],'serial')==0 or
  246. strcmp($fields[$field]['type'],'int')==0){
  247. $sql .= " $field = %d AND ";
  248. } else {
  249. $sql .= " $field = '%s' AND ";
  250. }
  251. array_push($dargs,$value);
  252. }
  253. $sql = substr($sql,0,-4); // get rid of the trailing 'AND'
  254. // finally perform the delete. If successful, return the updated record
  255. $previous_db = tripal_db_set_active('chado'); // use chado database
  256. $result = db_query($sql,$dargs);
  257. tripal_db_set_active($previous_db); // now use drupal database
  258. if($result){
  259. return true;
  260. }
  261. else {
  262. watchdog('tripal_core',"Cannot delete record in $table table. Match:" . print_r($match,1) . ". Values: ". print_r($values,1),array(),'WATCHDOG_ERROR');
  263. return false;
  264. }
  265. return false;
  266. }
  267. /**
  268. * Provides a generic routine for updating into any Chado table
  269. *
  270. * Use this function to update a record in any Chado table. The first
  271. * argument specifies the table for inserting, the second is an array
  272. * of values to matched for locating the record for updating, and the third
  273. * argument give the values to update. The arrays are mutli-dimensional such
  274. * that foreign key lookup values can be specified.
  275. *
  276. * @param $table
  277. * The name of the chado table for inserting
  278. * @param $match
  279. * An associative array containing the values for locating a record to update.
  280. * @param $values
  281. * An associative array containing the values for updating.
  282. *
  283. * @return
  284. * On success this function returns TRUE. On failure, it returns FALSE.
  285. *
  286. * Example usage:
  287. * @code
  288. $umatch = array(
  289. 'organism_id' => array(
  290. 'genus' => 'Citrus',
  291. 'species' => 'sinensis',
  292. ),
  293. 'uniquename' => 'orange1.1g000034m.g7',
  294. 'type_id' => array (
  295. 'cv_id' => array (
  296. 'name' => 'sequence',
  297. ),
  298. 'name' => 'gene',
  299. 'is_obsolete' => 0
  300. ),
  301. );
  302. $uvalues = array(
  303. 'name' => 'orange1.1g000034m.g',
  304. 'type_id' => array (
  305. 'cv_id' => array (
  306. 'name' => 'sequence',
  307. ),
  308. 'name' => 'mRNA',
  309. 'is_obsolete' => 0
  310. ),
  311. );
  312. * $result = tripal_core_chado_update('feature',$umatch,$uvalues);
  313. * @endcode
  314. * The above code species that a feature with a given uniquename, organism_id,
  315. * and type_id (the unique constraint for the feature table) will be updated.
  316. * The organism_id is specified as a nested array that uses the organism_id
  317. * foreign key constraint to lookup the specified values to find the exact
  318. * organism_id. The same nested struture is also used for specifying the
  319. * values to update. The function will find the record that matches the
  320. * columns specified and update the record with the avlues in the $uvalues array.
  321. *
  322. * @ingroup tripal_api
  323. */
  324. function tripal_core_chado_update($table,$match,$values){
  325. $update_values = array(); // contains the values to be updated
  326. $update_matches = array(); // contains the values for the where clause
  327. // get the table description
  328. $table_desc = module_invoke_all('chado_'.$table.'_schema');
  329. // get the values needed for matching in the SQL statement
  330. foreach ($match as $field => $value){
  331. if(is_array($value)){
  332. $results = tripal_core_chado_get_foreign_key($table_desc,$field,$value);
  333. if (sizeof($results) > 1) {
  334. 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);
  335. } elseif (sizeof($results) < 1) {
  336. 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);
  337. } else {
  338. $update_matches[$field] = $results[0];
  339. }
  340. }
  341. else {
  342. $update_matches[$field] = $value;
  343. }
  344. }
  345. // get the values used for updating
  346. foreach ($values as $field => $value){
  347. if(is_array($value)){
  348. $results = tripal_core_chado_get_foreign_key($table_desc,$field,$value);
  349. if (sizeof($results) > 1) {
  350. 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);
  351. } elseif (sizeof($results) < 1) {
  352. 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);
  353. } else {
  354. $update_values[$field] = $results[0];
  355. }
  356. }
  357. else {
  358. $update_values[$field] = $value;
  359. }
  360. }
  361. // now build the SQL statement
  362. $sql = "UPDATE {$table} SET ";
  363. $fields = $table_desc['fields'];
  364. $uargs = array();
  365. foreach($update_values as $field => $value){
  366. if(strcmp($fields[$field]['type'],'serial')==0 or
  367. strcmp($fields[$field]['type'],'int')==0){
  368. $sql .= " $field = %d, ";
  369. } else {
  370. $sql .= " $field = '%s', ";
  371. }
  372. array_push($uargs,$value);
  373. }
  374. $sql = substr($sql,0,-2); // get rid of the trailing comma & space
  375. $sql .= " WHERE ";
  376. foreach($update_matches as $field => $value){
  377. if(strcmp($fields[$field]['type'],'serial')==0 or
  378. strcmp($fields[$field]['type'],'int')==0){
  379. $sql .= " $field = %d AND ";
  380. } else {
  381. $sql .= " $field = '%s' AND ";
  382. }
  383. array_push($uargs,$value);
  384. }
  385. $sql = substr($sql,0,-4); // get rid of the trailing 'AND'
  386. // finally perform the update. If successful, return the updated record
  387. $previous_db = tripal_db_set_active('chado'); // use chado database
  388. $result = db_query($sql,$uargs);
  389. tripal_db_set_active($previous_db); // now use drupal database
  390. if($result){
  391. return true;
  392. }
  393. else {
  394. watchdog('tripal_core',"Cannot update record in $table table. Match:" . print_r($match,1) . ". Values: ". print_r($values,1),array(),'WATCHDOG_ERROR');
  395. return false;
  396. }
  397. return false;
  398. }
  399. /**
  400. * Provides a generic routine for selecting data from a Chado table
  401. *
  402. * Use this function to perform a simple select from any Chado table.
  403. *
  404. * @param $table
  405. * The name of the chado table for inserting
  406. * @param $columns
  407. * An array of column names
  408. * @param $values
  409. * An associative array containing the values for filtering the results. In the
  410. * case where multiple values for the same time are to be selected an additional
  411. * entry for the field should appear for each value
  412. * @param $options
  413. * An associative array of additional options where the key is the option
  414. * and the value is the value of that option.
  415. *
  416. * Additional Options Include:
  417. * - has_record
  418. * Set this argument to 'true' to have this function return a numeric
  419. * value for the number of recrods rather than the array of records. this
  420. * can be useful in 'if' statements to check the presence of particula records.
  421. * - return_sql
  422. * Set this to 'true' to have this function return an array where the first element is the sql
  423. * that would have been run and the second is an array of arguments.
  424. * - case_insensitive_columns
  425. * An array of columns to do a case insensitive search on.
  426. * - regex_columns
  427. * An array of columns where the value passed in should be treated as a regular expression
  428. *
  429. * @return
  430. * A database query result resource, FALSE if the query was not executed
  431. * correctly, or the number of records in the dataset if $has_record is set.
  432. *
  433. * Example usage:
  434. * @code
  435. * $columns = array('feature_id','name');
  436. * $values = array(
  437. * 'organism_id' => array(
  438. * 'genus' => 'Citrus',
  439. * 'species' => array('sinensis','clementina'),
  440. * ),
  441. * 'uniquename' => 'orange1.1g000034m.g',
  442. * 'type_id' => array (
  443. * 'cv_id' => array (
  444. * 'name' => 'sequence',
  445. * ),
  446. * 'name' => 'gene',
  447. * 'is_obsolete' => 0
  448. * ),
  449. * );
  450. * $result = tripal_core_chado_select('feature',$columns,$values);
  451. * @endcode
  452. * The above code selects a record from the feature table using the three fields
  453. * that uniquely identify a feature. The $columns array simply lists the columns
  454. * to select. The $values array is nested such that the organism is identified by
  455. * way of the organism_id foreign key constraint by specifying the genus and
  456. * species. The cvterm is also specified using its foreign key and the cv_id
  457. * for the cvterm is nested as well. In the example above, two different species
  458. * are allowed to match
  459. *
  460. * @ingroup tripal_api
  461. */
  462. function tripal_core_chado_select($table,$columns,$values,$options = null){
  463. if (!is_array($options)) { $options = array(); }
  464. if (!$options['case_insensitive_columns']) { $options['case_insensitive_columns'] = array(); }
  465. if (!$options['regex_columns']) { $options['regex_columns'] = array(); }
  466. if (!is_array($columns)){
  467. watchdog('tripal_feature', 'the $columns argument for tripal_core_chado_select must be an array.');
  468. return false;
  469. }
  470. if (!is_array($values)){
  471. watchdog('tripal_feature', 'the $values argument for tripal_core_chado_select must be an array.');
  472. return false;
  473. }
  474. // get the table description
  475. $table_desc = module_invoke_all('chado_'.$table.'_schema');
  476. $select = '';
  477. $from = '';
  478. $where = '';
  479. $args = array();
  480. foreach($values as $field => $value){
  481. $select[] = $field;
  482. if(is_array($value)){
  483. // if the user has specified multiple values for matching then this we
  484. // want to catch that and save them in our $where array, otherwise
  485. // we'll descend for a foreign key relationship
  486. if(array_values($value) === $value){
  487. $where[$field] = $value;
  488. } else {
  489. // select the value from the foreign key relationship for this value
  490. $foreign_options = array(
  491. 'regex_columns' => $options['regex_columns'],
  492. 'case_insensitive_columns' => $options['case_insensitive_columns']
  493. );
  494. $results = tripal_core_chado_get_foreign_key($table_desc,$field,$value, $foreign_options);
  495. if (sizeof($results) < 1) {
  496. // foreign key records are required
  497. // thus if none matched then return false and alert the admin through watchdog
  498. watchdog('tripal_core',
  499. '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',
  500. array('!table' => $table,
  501. '!columns' => '<pre>' . print_r($columns, TRUE) . '</pre>',
  502. '!values' => '<pre>' . print_r($values, TRUE) . '</pre>',
  503. '!field' => $field,
  504. ),
  505. WATCHDOG_WARNING);
  506. return false;
  507. } else {
  508. $where[$field] = $results;
  509. }
  510. }
  511. }
  512. else {
  513. //need to catch a 0 and make int if integer field
  514. if ($table_desc['fields'][$field]['type'] == 'int') {
  515. $where[$field][] = (int) $value;
  516. } else {
  517. $where[$field][] = $value;
  518. }
  519. }
  520. }
  521. // now build the SQL select statement
  522. if (empty($where)) {
  523. // sometimes want to select everything
  524. $sql = "SELECT " . implode(',',$columns) . " ";
  525. $sql .= "FROM {$table} ";
  526. } else {
  527. $sql = "SELECT " . implode(',',$columns) . " ";
  528. $sql .= "FROM {$table} ";
  529. $sql .= "WHERE ";
  530. foreach($where as $field => $value){
  531. if (count($value) > 1) {
  532. $sql .= "$field IN (".db_placeholders($value,'varchar').") AND ";
  533. foreach ($value as $v) { $args[] = $v; }
  534. } else {
  535. $operator = '=';
  536. if (in_array($field, $options['regex_columns'])) {
  537. $operator = '~*';
  538. }
  539. if (in_array($field, $options['case_insensitive_columns'])) {
  540. $sql .= "lower($field) $operator lower('%s') AND ";
  541. $args[] = $value[0];
  542. } else {
  543. $sql .= "$field $operator '%s' AND ";
  544. $args[] = $value[0];
  545. }
  546. }
  547. }
  548. $sql = substr($sql,0,-4); // get rid of the trailing 'AND'
  549. }
  550. // if the caller has requested the SQL rather than the results...
  551. // which happens in the case of wanting to use the Drupal pager, then do so
  552. if($options['return_sql']){
  553. return array('sql'=> $sql, 'args' => $args);
  554. }
  555. $previous_db = tripal_db_set_active('chado'); // use chado database
  556. $resource = db_query($sql,$args);
  557. tripal_db_set_active($previous_db); // now use drupal database
  558. $results = array();
  559. while ($r = db_fetch_object($resource)) {
  560. $results[] = $r;
  561. }
  562. if(!$options['has_record']){
  563. return $results;
  564. } else{
  565. return count($results);
  566. }
  567. }
  568. /**
  569. * Gets the value of a foreign key relationship
  570. *
  571. * This function is used by tripal_core_chado_select, tripal_core_chado_insert,
  572. * and tripal_core_chado_update to iterate through the associate array of
  573. * values that gets passed to each of those routines. The values array
  574. * is nested where foreign key contraints are used to specify a value that. See
  575. * documentation for any of those functions for further information.
  576. *
  577. * @param $table_desc
  578. * A table description for the table with the foreign key relationship to be identified generated by
  579. * hook_chado_<table name>_schema()
  580. * @param $field
  581. * The field in the table that is the foreign key.
  582. * @param $values
  583. * An associative array containing the values
  584. *
  585. * @return
  586. * A string containg the results of the foreign key lookup, or FALSE if failed.
  587. *
  588. * Example usage:
  589. * @code
  590. *
  591. * $values = array(
  592. * 'genus' => 'Citrus',
  593. * 'species' => 'sinensis',
  594. * );
  595. * $value = tripal_core_chado_get_foreign_key('feature','organism_id',$values);
  596. *
  597. * @endcode
  598. * The above code selects a record from the feature table using the three fields
  599. * that uniquely identify a feature. The $columns array simply lists the columns
  600. * to select. The $values array is nested such that the organism is identified by
  601. * way of the organism_id foreign key constraint by specifying the genus and
  602. * species. The cvterm is also specified using its foreign key and the cv_id
  603. * for the cvterm is nested as well.
  604. *
  605. * @ingroup tripal_api
  606. */
  607. function tripal_core_chado_get_foreign_key($table_desc,$field,$values, $options = null){
  608. if (!is_array($options)) { $options = array(); }
  609. if (!$options['case_insensitive_columns']) { $options['case_insensitive_columns'] = array(); }
  610. if (!$options['regex_columns']) { $options['regex_columns'] = array(); }
  611. // get the list of foreign keys for this table description and
  612. // iterate through those until we find the one we're looking for
  613. $fkeys = $table_desc['foreign keys'];
  614. if($fkeys){
  615. foreach($fkeys as $name => $def){
  616. if (is_array($def['table'])) {
  617. //foreign key was described 2X
  618. $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")).".";
  619. watchdog('tripal_core', $message);
  620. drupal_set_message($message,'error');
  621. continue;
  622. }
  623. $table = $def['table'];
  624. $columns = $def['columns'];
  625. // iterate through the columns of the foreign key relationship
  626. foreach($columns as $left => $right){
  627. // does the left column in the relationship match our field?
  628. if(strcmp($field,$left)==0){
  629. // the column name of the foreign key matches the field we want
  630. // so this is the right relationship. Now we want to select
  631. $select_cols = array($right);
  632. $result = tripal_core_chado_select($table,$select_cols,$values, $options);
  633. $fields = array();
  634. foreach ($result as $obj) {
  635. $fields[] = $obj->$right;
  636. }
  637. return $fields;
  638. }
  639. }
  640. }
  641. }
  642. else {
  643. // TODO: what do we do if we get to this point and we have a fk
  644. // relationship expected but we don't have any definition for one in the
  645. // table schema??
  646. $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.";
  647. watchdog('tripal_core', $message);
  648. drupal_set_message($message,'error');
  649. }
  650. return false;
  651. }
  652. /**
  653. * Generates an object containing the full details of a record(s) in chado.
  654. *
  655. * @todo Add expand_tables arrays
  656. *
  657. * This differs from the objects returned by tripal_core_chado_select in so far as all foreign key
  658. * relationships have been followed meaning you have more complete details. Thus this function
  659. * should be used whenever you need a full variable and tripal_core_chado_select should be used if
  660. * you only case about a few columns.
  661. *
  662. * @param $table
  663. * The name of the base table to generate a variable for
  664. * @param $values
  665. * A select values array that selects the records you want from the base table
  666. * (this has the same form as tripal_core_chado_select)
  667. * @return
  668. * Either an object (if only one record was selected from the base table)
  669. * or an array of objects (if more than one record was selected from the base table).
  670. *
  671. * Example Usage:
  672. * @code
  673. $values = array(
  674. 'name' => 'Medtr4g030710'
  675. );
  676. $features = tripal_core_generate_chado_var('feature', $values);
  677. * @endcode
  678. * This will return an object if there is only one feature with the name Medtr4g030710 or it will
  679. * return an array of feature objects if more than one feature has that name.
  680. *
  681. * Note to Module Designers: Fields can be excluded by default from these objects by implementing
  682. * one of the following hooks:
  683. * - hook_exclude_field_from_tablename_by_default (where tablename is the name of the table):
  684. * This hook allows you to add fields to be excluded on a per table basis. Simply implement
  685. * this hook to return an array of fields to be excluded. For example:
  686. * @code
  687. mymodule_exclude_field_from_feature_by_default() {
  688. return array('residues' => TRUE);
  689. }
  690. * @endcode
  691. * will ensure that feature.residues is ecluded from a feature object by default.
  692. * - hook_exclude_type_by_default:
  693. * This hook allows you to exclude fields from all tables that are of a given postgresql field
  694. * type. Simply implement this hook to return an array of postgresql types mapped to criteria.
  695. * Then all fields of that type where the criteria supplied returns TRUE will be excluded from
  696. * any table. Tokens available in criteria are &gt;field_value&lt; and &gt;field_name&lt; . For example:
  697. * @code
  698. mymodule_exclude_type_by_default() {
  699. return array('text' => 'length(&gt;field_value&lt; ) > 50');
  700. }
  701. * @endcode
  702. * 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.
  703. *
  704. * @ingroup tripal_api
  705. */
  706. function tripal_core_generate_chado_var($table, $values) {
  707. // get description for the current table----------------------------------------------------------
  708. $table_desc = module_invoke_all('chado_'.$table.'_schema');
  709. $table_primary_key = $table_desc['primary key'][0];
  710. $table_columns = array_keys($table_desc['fields']);
  711. // Expandable fields without value needed for criteria--------------------------------------------
  712. $all->expandable_fields = array();
  713. if ($table_desc['referring_tables']) {
  714. $all->expandable_tables = $table_desc['referring_tables'];
  715. } else {
  716. $all->expandable_tables = array();
  717. }
  718. $all->expandable_nodes = array();
  719. // Get fields to be removed by name.................................
  720. $fields_to_remove = module_invoke_all('exclude_field_from_'.$table.'_by_default');
  721. foreach ($fields_to_remove as $field_name => $criteria) {
  722. //replace &gt;field_name&lt; with the current field name &
  723. $criteria = preg_replace('/&gt;field_name&lt; /', $field_name, $criteria);
  724. // if field_value needed we can't deal with this field yet
  725. if (preg_match('/&gt;field_value&lt; /', $criteria)) { break; }
  726. //if criteria then remove from query
  727. $success = drupal_eval('<?php return '.$criteria.'; ?>');
  728. // watchdog('tripal_core',
  729. // 'Evaluating criteria (%criteria) for field %field in tripal_core_generate_chado_var for %table evaluated to %success',
  730. // array('%table' => $table, '%criteria'=>$criteria, '%field' => $field_name, '%success'=>$success),
  731. // WATCHDOG_NOTICE
  732. // );
  733. if ($success) {
  734. unset($table_columns[array_search($field_name, $table_columns)]);
  735. unset($fields_to_remove[$field_name]);
  736. $all->expandable_fields[] = $table . '.' . $field_name;
  737. }
  738. }
  739. //Get fields to be removed by type................................
  740. $types_to_remove = module_invoke_all('exclude_type_by_default');
  741. $field_types = array();
  742. foreach ($table_desc['fields'] as $field_name => $field_array) {
  743. $field_types[$field_array['type']][] = $field_name;
  744. }
  745. foreach ($types_to_remove as $field_type => $criteria) {
  746. // if there are fields of that type to remove
  747. if (is_array($field_types[$field_type])) {
  748. //replace &gt;field_name&lt; with the current field name &
  749. $criteria = preg_replace('/&gt;field_name&lt; /', $field_name, $criteria);
  750. foreach ($field_types[$field_type] as $field_name) {
  751. // if field_value needed we can't deal with this field yet
  752. if (preg_match('/&gt;field_value&lt; /', $criteria)) {
  753. $fields_to_remove[$field_name] = $criteria;
  754. continue;
  755. }
  756. // if field_value needed we can't deal with this field yet
  757. if (preg_match('/&gt;field_value&lt; /', $criteria)) { break; }
  758. //if criteria then remove from query
  759. $success = drupal_eval('<?php return '.$criteria.'; ?>');
  760. // watchdog('tripal_core',
  761. // 'Evaluating criteria (%criteria) for field %field of $type in tripal_core_generate_chado_var for %table evaluated to %success',
  762. // array('%table'=>$table, '%criteria'=>$criteria, '%field'=>$field_name, '%type'=>$field_type, '%success'=>$success),
  763. // WATCHDOG_NOTICE
  764. // );
  765. if ($success) {
  766. unset($table_columns[array_search($field_name, $table_columns)]);
  767. $all->expandable_fields[] = $table . '.' . $field_name;
  768. }
  769. } //end of foreach field of that type
  770. }
  771. } //end of foreach type to be removed
  772. // get the values for the record in the current table---------------------------------------------
  773. $results = tripal_core_chado_select($table, $table_columns, $values);
  774. foreach ($results as $key => $object) {
  775. // Add empty expandable_x arrays
  776. $object->expandable_fields = $all->expandable_fields;
  777. $object->expandable_tables = $all->expandable_tables;
  778. $object->expandable_nodes = $all->expandable_nodes;
  779. // add curent table
  780. $object->tablename = $table;
  781. // check if the current table maps to a node type-----------------------------------------------
  782. // if this table is connected to a node there will be a chado_tablename table in drupal
  783. if (db_table_exists('chado_'.$table)) {
  784. // that has a foreign key to this one ($table_desc['primary key'][0]
  785. // and to the node table (nid)
  786. $sql = "SELECT %s, nid FROM chado_%s WHERE %s=%d";
  787. $mapping = db_fetch_object(db_query(
  788. $sql,
  789. $table_primary_key,
  790. $table,
  791. $table_primary_key,
  792. $object->{$table_primary_key}
  793. ));
  794. if ($mapping->{$table_primary_key}) {
  795. $object->nid = $mapping->nid;
  796. $object->expandable_nodes[] = $table;
  797. }
  798. }
  799. // remove any fields where criteria need to be evalulated---------------------------------------
  800. foreach ($fields_to_remove as $field_name => $criteria) {
  801. if (!isset($object->{$field_name})) { break; }
  802. $criteria = preg_replace('/&gt;field_value&lt; /', $object->{$field_name}, $criteria);
  803. //if criteria then remove from query
  804. $success = drupal_eval('<?php return '.$criteria.'; ?>');
  805. // watchdog('tripal_core',
  806. // 'Evaluating criteria (%criteria) for field %field in tripal_core_generate_chado_var for %table evaluated to %success',
  807. // array('%table' => $table, '%criteria'=>$criteria, '%field' => $field_name, '%success'=>$success),
  808. // WATCHDOG_NOTICE
  809. // );
  810. if ($success) {
  811. unset($object->{$field_name});
  812. $object->expandable_fields[] = $table . '.' . $field_name;
  813. }
  814. }
  815. // recursively follow foreign key relationships nesting objects as we go------------------------
  816. if ($table_desc['foreign keys']) {
  817. foreach ($table_desc['foreign keys'] as $foreign_key_array) {
  818. $foreign_table = $foreign_key_array['table'];
  819. foreach ($foreign_key_array['columns'] as $foreign_key => $primary_key) {
  820. // Note: Foreign key is the field in the current table whereas primary_key is the field in
  821. // the table referenced by the foreign key
  822. //Dont do anything if the foreign key is empty
  823. if (empty($object->{$foreign_key})) {
  824. break;
  825. }
  826. // get the record from the foreign table
  827. $foreign_values = array($primary_key => $object->{$foreign_key});
  828. $foreign_object = tripal_core_generate_chado_var($foreign_table, $foreign_values);
  829. // add the foreign record to the current object in a nested manner
  830. $object->{$foreign_key} = $foreign_object;
  831. // Flatten expandable_x arrays so only in the bottom object
  832. if (is_array($object->{$foreign_key}->expandable_fields)) {
  833. $object->expandable_fields = array_merge(
  834. $object->expandable_fields,
  835. $object->{$foreign_key}->expandable_fields
  836. );
  837. unset($object->{$foreign_key}->expandable_fields);
  838. }
  839. if (is_array($object->{$foreign_key}->expandable_tables)) {
  840. $object->expandable_tables = array_merge(
  841. $object->expandable_tables,
  842. $object->{$foreign_key}->expandable_tables
  843. );
  844. unset($object->{$foreign_key}->expandable_tables);
  845. }
  846. if (is_array($object->{$foreign_key}->expandable_nodes)) {
  847. $object->expandable_nodes = array_merge(
  848. $object->expandable_nodes,
  849. $object->{$foreign_key}->expandable_nodes
  850. );
  851. unset($object->{$foreign_key}->expandable_nodes);
  852. }
  853. }
  854. }
  855. $results[$key] = $object;
  856. }
  857. }
  858. // check only one result returned
  859. if (sizeof($results) == 1) {
  860. // add results to object
  861. return $results[0];
  862. } elseif (!empty($results)) {
  863. return $results;
  864. } else {
  865. // no results returned
  866. }
  867. }
  868. /**
  869. * Retrieves fields/tables/nodes that were excluded by default from a variable and adds them
  870. *
  871. * This function exists to allow tripal_core_generate_chado_var() to excldue some
  872. * fields/tables/nodes from the default form of a variable without making it extremely difficult for
  873. * the tripal admin to get at these variables if he/she wants them.
  874. *
  875. * @param $object
  876. * This must be an object generated using tripal_core_generate_chado_var()
  877. * @param $type
  878. * Must be one of 'field', 'table', 'node'. Indicates what is being expanded.
  879. * @param $to_expand
  880. * The name of the field/table/node to be expanded
  881. *
  882. * @return
  883. * A chado object supplemented with the field/table/node requested to be expanded
  884. *
  885. * Example Usage:
  886. * @code
  887. // Get a chado object to be expanded
  888. $values = array(
  889. 'name' => 'Medtr4g030710'
  890. );
  891. $features = tripal_core_generate_chado_var('feature', $values);
  892. // Expand the organism node
  893. $feature = tripal_core_expand_chado_vars($feature, 'node', 'organism');
  894. // Expand the feature.residues field
  895. $feature = tripal_core_expand_chado_vars($feature, 'field', 'feature.residues');
  896. // Expand the feature properties (featureprop table)
  897. $feature = tripal_core_expand_chado_vars($feature, 'table', 'featureprop');
  898. * @endcode
  899. *
  900. * @ingroup tripal_api
  901. */
  902. function tripal_core_expand_chado_vars ($object, $type, $to_expand, $values = NULL) {
  903. $base_table = $object->tablename;
  904. // check to see if they are expanding an array of objects
  905. if (is_array($object)) {
  906. foreach ($object as $index => $o) {
  907. $object[$index] = tripal_core_expand_chado_vars($o,$type,$to_expand);
  908. }
  909. return $object;
  910. }
  911. switch ($type) {
  912. case "field": //--------------------------------------------------------------------------------
  913. if (preg_match('/(\w+)\.(\w+)/', $to_expand, $matches)) {
  914. $tablename = $matches[1];
  915. $fieldname = $matches[2];
  916. $table_desc = module_invoke_all('chado_'.$tablename.'_schema');
  917. $values = array();
  918. foreach($table_desc['primary key'] as $key) {
  919. $values[$key] = $object->{$key};
  920. }
  921. if ($base_table == $tablename) {
  922. //get the field
  923. $results = tripal_core_chado_select(
  924. $tablename,
  925. array($fieldname),
  926. $values
  927. );
  928. $object->{$fieldname} = $results[0]->{$fieldname};
  929. $object->expanded = $to_expand;
  930. } else {
  931. //We need to recurse -the field is in a nested object
  932. foreach ((array) $object as $field_name => $field_value) {
  933. if (is_object($field_value)) {
  934. $object->{$field_name} = tripal_core_expand_chado_vars(
  935. $field_value,
  936. 'field',
  937. $to_expand
  938. );
  939. }
  940. } //end of for each field in the current object
  941. }
  942. } else {
  943. watchdog(
  944. 'tripal_core',
  945. 'tripal_core_expand_chado_vars: Field (%field) not in the right format. It should be <tablename>.<fieldname>',
  946. WATCHDOG_ERROR
  947. );
  948. }
  949. break;
  950. case "table": //--------------------------------------------------------------------------------
  951. $foreign_table = $to_expand;
  952. $foreign_table_desc = module_invoke_all('chado_'.$foreign_table.'_schema');
  953. // If it's connected to the base table
  954. if ($foreign_table_desc['foreign keys'][$base_table]) {
  955. foreach ($foreign_table_desc['foreign keys'][$base_table]['columns'] as $left => $right) {
  956. if (!$object->{$right}) { break; }
  957. if (is_array($values)) {
  958. $values = array_merge($values, array($left => $object->{$right}) );
  959. } else {
  960. $values = array($left => $object->{$right});
  961. }
  962. $foreign_object = tripal_core_generate_chado_var(
  963. $foreign_table,
  964. $values
  965. );
  966. if ($foreign_object) {
  967. $object->{$foreign_table} = $foreign_object;
  968. $object->expanded = $to_expand;
  969. }
  970. }
  971. } else {
  972. //We need to recurse -the table has a relationship to one of the nested objects
  973. foreach ((array) $object as $field_name => $field_value) {
  974. // if we have a nested object ->expand the table in it
  975. if (is_object($field_value)) {
  976. $object->{$field_name} = tripal_core_expand_chado_vars(
  977. $field_value,
  978. 'table',
  979. $foreign_table
  980. );
  981. }
  982. }
  983. }
  984. break;
  985. case "node": //---------------------------------------------------------------------------------
  986. //if the node to be expanded is for our base table, then just expand it
  987. if ($object->tablename == $to_expand) {
  988. $node = node_load($object->nid);
  989. if ($node) {
  990. $object->expanded = $to_expand;
  991. $node->expandable_fields = $object->expandable_fields;
  992. unset($object->expandable_fields);
  993. $node->expandable_tables = $object->expandable_tables;
  994. unset($object->expandable_tables);
  995. $node->expandable_nodes = $object->expandable_nodes;
  996. unset($object->expandable_nodes);
  997. $node->{$base_table} = $object;
  998. $object = $node;
  999. } else {
  1000. watchdog(
  1001. 'tripal_core',
  1002. 'tripal_core_expand_chado_vars: No node matches the nid (%nid) supplied.',
  1003. array('%nid'=>$object->nid),
  1004. WATCHDOG_ERROR
  1005. );
  1006. } //end of if node
  1007. } else {
  1008. //We need to recurse -the node to expand is one of the nested objects
  1009. foreach ((array) $object as $field_name => $field_value) {
  1010. if (is_object($field_value)) {
  1011. $object->{$field_name} = tripal_core_expand_chado_vars(
  1012. $field_value,
  1013. 'node',
  1014. $to_expand
  1015. );
  1016. }
  1017. } //end of for each field in the current object
  1018. }
  1019. break;
  1020. default:
  1021. watchdog('tripal_core',
  1022. 'tripal_core_expand_chado_vars: Unrecognized type (%type). Should be one of "field", "table", "node".',
  1023. array('%type'=>$type),
  1024. WATCHDOG_ERROR
  1025. );
  1026. return FALSE;
  1027. }
  1028. //move extended array downwards-------------------------------------------------------------------
  1029. if (!$object->expanded) {
  1030. //if there's no extended field then go hunting for it
  1031. foreach ( (array)$object as $field_name => $field_value) {
  1032. if (is_object($field_value)) {
  1033. if (isset($field_value->expanded)) {
  1034. $object->expanded = $field_value->expanded;
  1035. unset($field_value->expanded);
  1036. }
  1037. }
  1038. }
  1039. }
  1040. //try again becasue now we might have moved it down
  1041. if ($object->expanded) {
  1042. $expandable_name = 'expandable_'.$type.'s';
  1043. if ($object->{$expandable_name}) {
  1044. $key_to_remove = array_search($object->expanded, $object->{$expandable_name});
  1045. unset($object->{$expandable_name}[$key_to_remove]);
  1046. unset($object->expanded);
  1047. } else {
  1048. // if there is an expandable array then we've reached the base object
  1049. // if we get here and don't have anything expanded then something went wrong
  1050. // watchdog(
  1051. // 'tripal_core',
  1052. // 'tripal_core_expand_chado_vars: Unable to expand the %type %to_expand',
  1053. // array('%type'=>$type, '%to_expand'=>$to_expand),
  1054. // WATCHDOG_ERROR
  1055. // );
  1056. } //end of it we've reached the base object
  1057. }
  1058. return $object;
  1059. }
  1060. /**
  1061. * Implements hook_exclude_type_by_default()
  1062. *
  1063. * This hooks allows fields of a specified type that match a specified criteria to be excluded by
  1064. * default from any table when tripal_core_generate_chado_var() is called. Keep in mind that if
  1065. * fields are excluded by default they can always be expanded at a later date using
  1066. * tripal_core_expand_chado_vars().
  1067. *
  1068. * Criteria are php strings that evaluate to either TRUE or FALSE. These strings are evaluated using
  1069. * drupal_eval() which suppresses syntax errors and throws watchdog entries of type php. There are
  1070. * also watchdog entries of type tripal_core stating the exact criteria evaluated. Criteria can
  1071. * contain the following tokens:
  1072. * - &gt;field_name&lt;
  1073. * Replaced by the name of the field to be excluded
  1074. * - &gt;field_value&lt;
  1075. * Replaced by the value of the field in the current record
  1076. * Also keep in mind that if your criteria doesn't contain the &gt;field_value&lt; token then it will be
  1077. * evaluated before the query is executed and if the field is excluded it won't be included in the
  1078. * query.
  1079. *
  1080. * @return
  1081. * An array of type => criteria where the type is excluded if the criteria evaluates to TRUE
  1082. *
  1083. * @ingroup tripal_api
  1084. */
  1085. function tripal_core_exclude_type_by_default() {
  1086. return array('text' => "strlen('&gt;field_value&lt; ') > 100");
  1087. }
  1088. /**
  1089. * Implements hook_exclude_field_from_<tablename>_by_default()
  1090. *
  1091. * This hooks allows fields from a specified table that match a specified criteria to be excluded by
  1092. * default from any table when tripal_core_generate_chado_var() is called. Keep in mind that if
  1093. * fields are excluded by default they can always be expanded at a later date using
  1094. * tripal_core_expand_chado_vars().
  1095. *
  1096. * Criteria are php strings that evaluate to either TRUE or FALSE. These strings are evaluated using
  1097. * drupal_eval() which suppresses syntax errors and throws watchdog entries of type php. There are
  1098. * also watchdog entries of type tripal_core stating the exact criteria evaluated. Criteria can
  1099. * contain the following tokens:
  1100. * - &gt;field_name&lt;
  1101. * Replaced by the name of the field to be excluded
  1102. * - &gt;field_value&lt;
  1103. * Replaced by the value of the field in the current record
  1104. * Also keep in mind that if your criteria doesn't contain the &gt;field_value&lt; token then it will be
  1105. * evaluated before the query is executed and if the field is excluded it won't be included in the
  1106. * query.
  1107. *
  1108. * @return
  1109. * An array of type => criteria where the type is excluded if the criteria evaluates to TRUE
  1110. *
  1111. * @ingroup tripal_api
  1112. */
  1113. function tripal_core_exclude_field_from_feature_by_default() {
  1114. return array();
  1115. }
  1116. /************************************************************************
  1117. * Use this function instead of db_query() to avoid switching databases
  1118. * when making query to the chado database
  1119. */
  1120. function chado_query($sql) {
  1121. $args = func_get_args();
  1122. array_shift($args);
  1123. $sql = db_prefix_tables($sql);
  1124. if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
  1125. $args = $args[0];
  1126. }
  1127. _db_query_callback($args, TRUE);
  1128. $sql = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $sql);
  1129. $previous_db = db_set_active('chado');
  1130. $results = _db_query($sql);
  1131. db_set_active($previous_db);
  1132. return $results;
  1133. }
  1134. /************************************************************************
  1135. * Get chado id for a node. E.g, if you want to get 'analysis_id' from the
  1136. * 'analysis' table for a synced 'chado_analysis' node, use:
  1137. * $analysis_id = chado_get_id_for_node ('analysis', $node)
  1138. * Likewise,
  1139. * $organism_id = chado_get_id_for_node ('organism', $node)
  1140. * $feature_id = chado_get_id_for_node ('feature', $node)
  1141. */
  1142. function chado_get_id_for_node ($table, $node) {
  1143. return db_result(db_query("SELECT $table"."_id FROM {chado_".$table."} WHERE nid = $node->nid"));
  1144. }
  1145. /************************************************************************
  1146. * Get node id for a chado feature/organism/analysis. E.g, if you want to
  1147. * get the node id for an analysis, use:
  1148. * $nid = chado_get_node_id ('analysis', $analysis_id)
  1149. * Likewise,
  1150. * $nid = chado_get_node_id ('organism', $organism_id)
  1151. * $nid = chado_get_node_id ('feature', $feature_id)
  1152. */
  1153. function chado_get_node_id ($table, $id) {
  1154. return db_result(db_query("SELECT nid FROM {chado_".$table."} WHERE $table"."_id = $id"));
  1155. }