tripal_core.api.inc 65 KB

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