tripal_core.api.inc 64 KB

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