tripal_core.api.inc 63 KB

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