tripal_core.api.inc 63 KB

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