tripal_core.api.inc 54 KB

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