tripal_core.api.inc 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087
  1. <?php
  2. require_once "tripal_core.schema.api.inc";
  3. /**
  4. * @file
  5. * The Tripal Core API
  6. *
  7. * This file provides the API needed for all other Tripal and Tripal dependent
  8. * modules.
  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. * @defgroup tripal_chado_api Core Module Chado API
  24. * @{
  25. * Provides an application programming interface (API) to manage data withing the Chado database.
  26. * This includes functions for selecting, inserting, updating and deleting records
  27. * in Chado tables. The functions will ensure proper integrity contraints are met
  28. * for inserts and updates.
  29. *
  30. * Also, a set of functions is provided for creating template variables. First,
  31. * is the tripal_core_generate_chado_vars which is used to select one ore more
  32. * records from a table and return an array with foreign key relationships fully
  33. * populated. For example, if selecting a feature, the organism_id and type_id
  34. * would be present in the returned array as a nested array with their respective
  35. * foreign keys also nested. The only fields that are not included are text
  36. * fields (which may be very large) or many-to-many foreign key relationships.
  37. * However, these fields and relationships can be expanded using the
  38. * tripal_core_expand_chado_vars.
  39. *
  40. * When a row from a chado table is selected using these two functions, it provides
  41. * a way for users who want to cutomize Drupal template files to access all data
  42. * associate with a specific record.
  43. *
  44. * Finally, the property tables in Chado generally follow the same format. Therefore
  45. * there is a set of functions for inserting, updating and deleting properties for
  46. * any table. This provides quick lookup of properties (provided the CV term is
  47. * known).
  48. *
  49. * @}
  50. * @ingroup tripal_api
  51. *
  52. * @defgroup tripal_files_api Core Module Files API
  53. * @{
  54. * Provides an application programming interface (API) for managing files within
  55. * the Tripal data directory structure.
  56. *
  57. * @}
  58. * @ingroup tripal_api
  59. /**
  60. * Provides a generic routine for inserting into any Chado table
  61. *
  62. * Use this function to insert a record into any Chado table. The first
  63. * argument specifies the table for inserting and the second is an array
  64. * of values to be inserted. The array is mutli-dimensional such that
  65. * foreign key lookup values can be specified.
  66. *
  67. * @param $table
  68. * The name of the chado table for inserting
  69. * @param $values
  70. * An associative array containing the values for inserting.
  71. *
  72. * @return
  73. * On success this function returns TRUE. On failure, it returns FALSE.
  74. *
  75. * Example usage:
  76. * @code
  77. * $values = array(
  78. * 'organism_id' => array(
  79. * 'genus' => 'Citrus',
  80. * 'species' => 'sinensis',
  81. * ),
  82. * 'name' => 'orange1.1g000034m.g',
  83. * 'uniquename' => 'orange1.1g000034m.g',
  84. * 'type_id' => array (
  85. * 'cv_id' => array (
  86. * 'name' => 'sequence',
  87. * ),
  88. * 'name' => 'gene',
  89. * 'is_obsolete' => 0
  90. * ),
  91. * );
  92. * $result = tripal_core_chado_insert('feature',$values);
  93. * @endcode
  94. * The above code inserts a record into the feature table. The $values array is
  95. * nested such that the organism is selected by way of the organism_id foreign
  96. * key constraint by specifying the genus and species. The cvterm is also
  97. * specified using its foreign key and the cv_id for the cvterm is nested as
  98. * well.
  99. *
  100. * @ingroup tripal_chado_api
  101. */
  102. function tripal_core_chado_insert($table, $values, $options) {
  103. $insert_values = array();
  104. $chado_db = tripal_db_persistent_chado();
  105. // Determine plan of action
  106. if ($options['statement_name']) {
  107. $prepared = TRUE;
  108. $connection = tripal_db_persistent_chado();
  109. if ($options['prepare']) {
  110. $build_sql = TRUE;
  111. }
  112. else {
  113. $build_sql = FALSE;
  114. }
  115. }
  116. else {
  117. $build_sql = TRUE;
  118. }
  119. // get the table description
  120. $table_desc = module_invoke_all('chado_' . $table . '_schema');
  121. if (empty($table_desc)) {
  122. watchdog('tripal_core', 'tripal_core_chado_insert: There is no table description for !table_name', array('!table_name' => $table), WATCHDOG_WARNING);
  123. }
  124. // iterate through the values array and create a new 'insert_values' array
  125. // that has all the values needed for insert with all foreign relationsihps
  126. // resolved.
  127. foreach ($values as $field => $value) {
  128. if (is_array($value)) {
  129. // select the value from the foreign key relationship for this value
  130. $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value);
  131. if (sizeof($results) > 1) {
  132. 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);
  133. }
  134. elseif (sizeof($results) < 1) {
  135. //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);
  136. }
  137. else {
  138. $insert_values[$field] = $results[0];
  139. }
  140. }
  141. else {
  142. $insert_values[$field] = $value;
  143. }
  144. }
  145. // check for violation of any unique constraints
  146. $ukeys = $table_desc['unique keys'];
  147. $ukselect_cols = array();
  148. $ukselect_vals = array();
  149. if ($ukeys) {
  150. foreach ($ukeys as $name => $fields) {
  151. foreach ($fields as $index => $field) {
  152. // build the arrays for performing a select that will check the contraint
  153. array_push($ukselect_cols, $field);
  154. $ukselect_vals[$field] = $insert_values[$field];
  155. }
  156. // now check the constraint
  157. if (tripal_core_chado_select($table, $ukselect_cols, $ukselect_vals)) {
  158. watchdog('tripal_core', "tripal_core_chado_insert: Cannot insert duplicate record into $table table: " . print_r($values, 1), array(), 'WATCHDOG_ERROR');
  159. return FALSE;
  160. }
  161. }
  162. }
  163. // if trying to insert a field that is the primary key, make sure it also is unique
  164. $pkey = $table_desc['primary key'][0];
  165. if ($insert_values[$pkey]) {
  166. if (tripal_core_chado_select($table, array($pkey), array($pkey => $insert_values[$pkey]))) {
  167. watchdog('tripal_core', "tripal_core_chado_insert: Cannot insert duplicate primary key into $table table: " . print_r($values, 1), array(), 'WATCHDOG_ERROR');
  168. return FALSE;
  169. }
  170. }
  171. // make sure required fields have a value
  172. $fields = $table_desc['fields'];
  173. if (!is_array($fields)) {
  174. $fields = array();
  175. watchdog('tripal_core', "tripal_core_chado_insert: %table not defined in tripal schema api", array('%table' => $table), 'WATCHDOG WARNING');
  176. }
  177. foreach ($fields as $field => $def) {
  178. // a field is considered missing if it cannot be NULL and there is no default
  179. // value for it or it is of type 'serial'
  180. if ($def['not NULL'] == 1 and !array_key_exists($field, $insert_values) and !isset($def['default']) and strcmp($def['type'], serial) != 0) {
  181. watchdog('tripal_core', "tripal_core_chado_insert: Field $table.$field cannot be NULL: " . print_r($values, 1), array(), 'WATCHDOG_ERROR');
  182. return FALSE;
  183. }
  184. }
  185. // Now build the insert SQL statement
  186. $ifields = array(); //contains the names of the fields
  187. $ivalues = array(); //contains the values of the fields
  188. $itypes = array(); // contains %d/%s placeholders for the sql query
  189. $iplaceholders = array(); // contains $1/$2 placeholders for the prepare query
  190. $idatatypes = array(); //contains the data type of the fields (int, text, etc.)
  191. $i = 1;
  192. foreach ($insert_values as $field => $value){
  193. $ifields[] = $field;
  194. $ivalues[] = $value;
  195. $iplaceholders[] = '$'.$i;
  196. $i++;
  197. if(strcmp($value,'__NULL__')==0){
  198. $itypes[] = "NULL";
  199. $idatatypes[] = "NULL";
  200. }
  201. elseif(strcmp($fields[$field]['type'],'serial')==0 or
  202. strcmp($fields[$field]['type'],'int')==0){
  203. $itypes[] = "%d";
  204. $idatatypes[] = 'int';
  205. }
  206. else {
  207. $itypes[] = "'%s'";
  208. $idatatypes[] = 'text';
  209. }
  210. }
  211. if ($build_sql) {
  212. // prepare the statement
  213. if ($prepared) {
  214. $prepare_sql = "PREPARE " . $options['statement_name'] . " (" . implode(', ', $idatatypes) . ") AS INSERT INTO {$table} (" . implode(", ", $ifields) . ") VALUES (" . implode(", ", $iplaceholders) . ")";
  215. $status = chado_query($prepare_sql);
  216. if (!$status) {
  217. watchdog('tripal_core',"tripal_core_chado_insert: not able to prepare '%name' statement for: %sql", array('%name' => $options['statement_name'], '%sql' => $sql), 'WATCHDOG ERROR');
  218. return FALSE;
  219. }
  220. } else {
  221. $sql = "INSERT INTO {$table} (" . implode(", ",$ifields) . ") VALUES (". implode(", ",$itypes) .")";
  222. }
  223. }
  224. // finally perform the insert.
  225. if ($prepared) {
  226. $sql = "EXECUTE " . $options['statement_name'] . "(" . implode(", ", $itypes) . ")";
  227. $result = chado_query($sql, $ivalues);
  228. if ($result) {
  229. // add primary keys to values before return
  230. $primary_key = array();
  231. if (!is_array($table_desc['primary key'])) {
  232. $table_desc['primary key'] = array();
  233. watchdog('tripal_core',"tripal_core_chado_insert: %table not defined in tripal schema api", array('%table' => $table), 'WATCHDOG WARNING');
  234. }
  235. foreach ($table_desc['primary key'] as $field) {
  236. $value = db_last_insert_id($table, $field);
  237. $values[$field] = $value;
  238. }
  239. return $values;
  240. }
  241. else {
  242. watchdog('tripal_core',"tripal_core_chado_insert: not able to execute prepared statement '%name' with values: %values", array('%name' => $options['statement_name'], '%values' => print_r($values,1)), 'WATCHDOG ERROR');
  243. return FALSE;
  244. }
  245. }
  246. else {
  247. $previous_db = tripal_db_set_active('chado'); // use chado database
  248. $result = db_query($sql, $ivalues);
  249. tripal_db_set_active($previous_db); // now use drupal database
  250. if ($result) {
  251. // add primary keys to values before return
  252. $primary_key = array();
  253. if (!is_array($table_desc['primary key'])) {
  254. $table_desc['primary key'] = array();
  255. watchdog('tripal_core', "tripal_core_chado_insert: %table not defined in tripal schema api", array('%table' => $table), 'WATCHDOG WARNING');
  256. }
  257. foreach ($table_desc['primary key'] as $field) {
  258. $value = db_last_insert_id($table, $field);
  259. $values[$field] = $value;
  260. }
  261. return $values;
  262. }
  263. else {
  264. watchdog('tripal_core', "tripal_core_chado_insert: Cannot insert record into $table table: " . print_r($values, 1), array(), 'WATCHDOG_ERROR');
  265. return FALSE;
  266. }
  267. }
  268. return FALSE;
  269. }
  270. /**
  271. * Provides a generic function for deleting a record(s) from any chado table
  272. *
  273. * Use this function to delete a record(s) in any Chado table. The first
  274. * argument specifies the table to delete from and the second is an array
  275. * of values to match for locating the record(s) to be deleted. The arrays
  276. * are mutli-dimensional such that foreign key lookup values can be specified.
  277. *
  278. * @param $table
  279. * The name of the chado table for inserting
  280. * @param $match
  281. * An associative array containing the values for locating a record to update.
  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 deleted.
  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 all records that match the
  320. * columns specified and delete them.
  321. *
  322. * @ingroup tripal_chado_api
  323. */
  324. function tripal_core_chado_delete($table, $match) {
  325. $delete_matches = array(); // contains the values for the where clause
  326. // get the table description
  327. $table_desc = module_invoke_all('chado_' . $table . '_schema');
  328. // get the values needed for matching in the SQL statement
  329. foreach ($match as $field => $value) {
  330. if (is_array($value)) {
  331. // if the user has specified an array of values to delete rather than
  332. // FK relationships the keep those in our match
  333. if (array_values($value) === $value) {
  334. $delete_matches[$field] = $value;
  335. }
  336. else {
  337. $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value);
  338. if (sizeof($results) > 1) {
  339. 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);
  340. }
  341. elseif (sizeof($results) < 1) {
  342. //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);
  343. }
  344. else {
  345. $delete_matches[$field] = $results[0];
  346. }
  347. }
  348. }
  349. else {
  350. $delete_matches[$field] = $value;
  351. }
  352. }
  353. // now build the SQL statement
  354. $sql = "DELETE FROM {$table} WHERE ";
  355. $dargs = array();
  356. foreach ($delete_matches as $field => $value) {
  357. if (count($value) > 1) {
  358. $sql .= "$field IN (" . db_placeholders($value, 'varchar') . ") AND ";
  359. foreach ($value as $v) {
  360. $dargs[] = $v;
  361. }
  362. }
  363. else {
  364. if (strcmp($value, '__NULL__') == 0) {
  365. $sql .= " $field = NULL AND ";
  366. }
  367. elseif (strcmp($fields[$field]['type'], 'serial') == 0 or
  368. strcmp($fields[$field]['type'], 'int') == 0) {
  369. $sql .= " $field = %d AND ";
  370. }
  371. else {
  372. $sql .= " $field = '%s' AND ";
  373. }
  374. array_push($dargs, $value);
  375. }
  376. }
  377. $sql = drupal_substr($sql, 0, -4); // get rid of the trailing 'AND'
  378. // finally perform the delete. If successful, return the updated record
  379. $previous_db = tripal_db_set_active('chado'); // use chado database
  380. $result = db_query($sql, $dargs);
  381. tripal_db_set_active($previous_db); // now use drupal database
  382. if ($result) {
  383. return TRUE;
  384. }
  385. else {
  386. watchdog('tripal_core', "Cannot delete record in $table table. Match:" . print_r($match, 1) . ". Values: ". print_r($values, 1), array(), 'WATCHDOG_ERROR');
  387. return FALSE;
  388. }
  389. return FALSE;
  390. }
  391. /**
  392. * Provides a generic routine for updating into any Chado table
  393. *
  394. * Use this function to update a record in any Chado table. The first
  395. * argument specifies the table for inserting, the second is an array
  396. * of values to matched for locating the record for updating, and the third
  397. * argument give the values to update. The arrays are mutli-dimensional such
  398. * that foreign key lookup values can be specified.
  399. *
  400. * @param $table
  401. * The name of the chado table for inserting
  402. * @param $match
  403. * An associative array containing the values for locating a record to update.
  404. * @param $values
  405. * An associative array containing the values for updating.
  406. *
  407. * @return
  408. * On success this function returns TRUE. On failure, it returns FALSE.
  409. *
  410. * Example usage:
  411. * @code
  412. $umatch = array(
  413. 'organism_id' => array(
  414. 'genus' => 'Citrus',
  415. 'species' => 'sinensis',
  416. ),
  417. 'uniquename' => 'orange1.1g000034m.g7',
  418. 'type_id' => array (
  419. 'cv_id' => array (
  420. 'name' => 'sequence',
  421. ),
  422. 'name' => 'gene',
  423. 'is_obsolete' => 0
  424. ),
  425. );
  426. $uvalues = array(
  427. 'name' => 'orange1.1g000034m.g',
  428. 'type_id' => array (
  429. 'cv_id' => array (
  430. 'name' => 'sequence',
  431. ),
  432. 'name' => 'mRNA',
  433. 'is_obsolete' => 0
  434. ),
  435. );
  436. * $result = tripal_core_chado_update('feature',$umatch,$uvalues);
  437. * @endcode
  438. * The above code species that a feature with a given uniquename, organism_id,
  439. * and type_id (the unique constraint for the feature table) will be updated.
  440. * The organism_id is specified as a nested array that uses the organism_id
  441. * foreign key constraint to lookup the specified values to find the exact
  442. * organism_id. The same nested struture is also used for specifying the
  443. * values to update. The function will find the record that matches the
  444. * columns specified and update the record with the avlues in the $uvalues array.
  445. *
  446. * @ingroup tripal_chado_api
  447. */
  448. function tripal_core_chado_update($table, $match, $values) {
  449. $update_values = array(); // contains the values to be updated
  450. $update_matches = array(); // contains the values for the where clause
  451. // get the table description
  452. $table_desc = module_invoke_all('chado_' . $table . '_schema');
  453. // get the values needed for matching in the SQL statement
  454. foreach ($match as $field => $value) {
  455. if (is_array($value)) {
  456. $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value);
  457. if (sizeof($results) > 1) {
  458. 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);
  459. }
  460. elseif (sizeof($results) < 1) {
  461. //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);
  462. }
  463. else {
  464. $update_matches[$field] = $results[0];
  465. }
  466. }
  467. else {
  468. $update_matches[$field] = $value;
  469. }
  470. }
  471. // get the values used for updating
  472. foreach ($values as $field => $value) {
  473. if (is_array($value)) {
  474. $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value);
  475. if (sizeof($results) > 1) {
  476. 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);
  477. }
  478. elseif (sizeof($results) < 1) {
  479. //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);
  480. }
  481. else {
  482. $update_values[$field] = $results[0];
  483. }
  484. }
  485. else {
  486. $update_values[$field] = $value;
  487. }
  488. }
  489. // now build the SQL statement
  490. $sql = "UPDATE {$table} SET ";
  491. $fields = $table_desc['fields'];
  492. $uargs = array();
  493. foreach ($update_values as $field => $value) {
  494. if (strcmp($value, '__NULL__') == 0) {
  495. $sql .= " $field = NULL, ";
  496. }
  497. elseif (strcmp($fields[$field]['type'], 'serial')==0 or
  498. strcmp($fields[$field]['type'], 'int')==0) {
  499. $sql .= " $field = %d, ";
  500. }
  501. else {
  502. $sql .= " $field = '%s', ";
  503. }
  504. array_push($uargs, $value);
  505. }
  506. $sql = drupal_substr($sql, 0, -2); // get rid of the trailing comma & space
  507. $sql .= " WHERE ";
  508. foreach ($update_matches as $field => $value) {
  509. if (strcmp($value, '__NULL__')==0) {
  510. $sql .= " $field = NULL AND ";
  511. }
  512. elseif (strcmp($fields[$field]['type'], 'serial')==0 or
  513. strcmp($fields[$field]['type'], 'int')==0) {
  514. $sql .= " $field = %d AND ";
  515. }
  516. else {
  517. $sql .= " $field = '%s' AND ";
  518. }
  519. array_push($uargs, $value);
  520. }
  521. $sql = drupal_substr($sql, 0, -4); // get rid of the trailing 'AND'
  522. // finally perform the update. If successful, return the updated record
  523. $previous_db = tripal_db_set_active('chado'); // use chado database
  524. $result = db_query($sql, $uargs);
  525. tripal_db_set_active($previous_db); // now use drupal database
  526. if ($result) {
  527. return TRUE;
  528. }
  529. else {
  530. watchdog('tripal_core', "Cannot update record in $table table. Match:" . print_r($match, 1) . ". Values: ". print_r($values, 1), array(), 'WATCHDOG_ERROR');
  531. return FALSE;
  532. }
  533. return FALSE;
  534. }
  535. /**
  536. * Provides a generic routine for selecting data from a Chado table
  537. *
  538. * Use this function to perform a simple select from any Chado table.
  539. *
  540. * @param $table
  541. * The name of the chado table for inserting
  542. * @param $columns
  543. * An array of column names
  544. * @param $values
  545. * An associative array containing the values for filtering the results. In the
  546. * case where multiple values for the same time are to be selected an additional
  547. * entry for the field should appear for each value
  548. * @param $options
  549. * An associative array of additional options where the key is the option
  550. * and the value is the value of that option.
  551. *
  552. * Additional Options Include:
  553. * - has_record
  554. * Set this argument to 'TRUE' to have this function return a numeric
  555. * value for the number of recrods rather than the array of records. this
  556. * can be useful in 'if' statements to check the presence of particula records.
  557. * - return_sql
  558. * Set this to 'TRUE' to have this function return an array where the first
  559. * element is the sql that would have been run and the second is an array of
  560. * arguments.
  561. * - case_insensitive_columns
  562. * An array of columns to do a case insensitive search on.
  563. * - regex_columns
  564. * An array of columns where the value passed in should be treated as a regular expression
  565. * - order_by
  566. * An associative array containing the column names of the table as keys
  567. * and the type of sort (i.e. ASC, DESC) as the values. The results in the
  568. * query will be sorted by the key values in the direction listed by the value
  569. *
  570. * @return
  571. * A database query result resource, FALSE if the query was not executed
  572. * correctly, or the number of records in the dataset if $has_record is set.
  573. *
  574. * Example usage:
  575. * @code
  576. * $columns = array('feature_id', 'name');
  577. * $values = array(
  578. * 'organism_id' => array(
  579. * 'genus' => 'Citrus',
  580. * 'species' => array('sinensis', 'clementina'),
  581. * ),
  582. * 'uniquename' => 'orange1.1g000034m.g',
  583. * 'type_id' => array (
  584. * 'cv_id' => array (
  585. * 'name' => 'sequence',
  586. * ),
  587. * 'name' => 'gene',
  588. * 'is_obsolete' => 0
  589. * ),
  590. * );
  591. * $result = tripal_core_chado_select('feature',$columns,$values);
  592. * @endcode
  593. * The above code selects a record from the feature table using the three fields
  594. * that uniquely identify a feature. The $columns array simply lists the columns
  595. * to select. The $values array is nested such that the organism is identified by
  596. * way of the organism_id foreign key constraint by specifying the genus and
  597. * species. The cvterm is also specified using its foreign key and the cv_id
  598. * for the cvterm is nested as well. In the example above, two different species
  599. * are allowed to match
  600. *
  601. * @ingroup tripal_chado_api
  602. */
  603. function tripal_core_chado_select($table, $columns, $values, $options = NULL) {
  604. if (!is_array($options)) {
  605. $options = array();
  606. }
  607. if (!$options['case_insensitive_columns']) {
  608. $options['case_insensitive_columns'] = array();
  609. }
  610. if (!$options['regex_columns']) {
  611. $options['regex_columns'] = array();
  612. }
  613. if (!$options['order_by']) {
  614. $options['order_by'] = array();
  615. }
  616. if (!is_array($columns)) {
  617. watchdog('tripal_core', 'the $columns argument for tripal_core_chado_select must be an array.');
  618. return FALSE;
  619. }
  620. if (!is_array($values)) {
  621. watchdog('tripal_core', 'the $values argument for tripal_core_chado_select must be an array.');
  622. return FALSE;
  623. }
  624. // get the table description
  625. $table_desc = module_invoke_all('chado_' . $table . '_schema');
  626. $select = '';
  627. $from = '';
  628. $where = '';
  629. $args = array();
  630. foreach ($values as $field => $value) {
  631. $select[] = $field;
  632. if (is_array($value)) {
  633. // if the user has specified multiple values for matching then this we
  634. // want to catch that and save them in our $where array, otherwise
  635. // we'll descend for a foreign key relationship
  636. if (array_values($value) === $value) {
  637. $where[$field] = $value;
  638. }
  639. else {
  640. // select the value from the foreign key relationship for this value
  641. $foreign_options = array(
  642. 'regex_columns' => $options['regex_columns'],
  643. 'case_insensitive_columns' => $options['case_insensitive_columns']
  644. );
  645. $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value, $foreign_options);
  646. if (count($results) ==0) {
  647. // foreign key records are required
  648. // thus if none matched then return FALSE and alert the admin through watchdog
  649. //watchdog('tripal_core',
  650. // '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',
  651. // array('!table' => $table,
  652. // '!columns' => '<pre>' . print_r($columns, TRUE) . '</pre>',
  653. // '!values' => '<pre>' . print_r($values, TRUE) . '</pre>',
  654. // '!field' => $field,
  655. // ),
  656. // WATCHDOG_WARNING);
  657. return FALSE;
  658. }
  659. else {
  660. $where[$field] = $results;
  661. }
  662. }
  663. }
  664. else {
  665. //need to catch a 0 and make int if integer field
  666. if ($table_desc['fields'][$field]['type'] == 'int') {
  667. $where[$field][] = (int) $value;
  668. }
  669. else {
  670. $where[$field][] = $value;
  671. }
  672. }
  673. }
  674. // now build the SQL select statement
  675. if (empty($where)) {
  676. // sometimes want to select everything
  677. $sql = "SELECT " . implode(', ', $columns) . " ";
  678. $sql .= "FROM {$table} ";
  679. }
  680. else {
  681. $sql = "SELECT " . implode(', ', $columns) . " ";
  682. $sql .= "FROM {$table} ";
  683. $sql .= "WHERE ";
  684. foreach ($where as $field => $value) {
  685. if (count($value) > 1) {
  686. $sql .= "$field IN (" . db_placeholders($value, 'varchar') . ") AND ";
  687. foreach ($value as $v) {
  688. $args[] = $v;
  689. }
  690. }
  691. else {
  692. $operator = '=';
  693. if (in_array($field, $options['regex_columns'])) {
  694. $operator = '~*';
  695. }
  696. if (in_array($field, $options['case_insensitive_columns'])) {
  697. $sql .= "lower($field) $operator lower('%s') AND ";
  698. $args[] = $value[0];
  699. }
  700. else {
  701. $sql .= "$field $operator '%s' AND ";
  702. $args[] = $value[0];
  703. }
  704. }
  705. }
  706. $sql = drupal_substr($sql, 0, -4); // get rid of the trailing 'AND '
  707. }
  708. // finally add any ordering of the results to the SQL statement
  709. if (count($options['order_by']) > 0) {
  710. $sql .= " ORDER BY ";
  711. foreach ($options['order_by'] as $field => $dir) {
  712. $sql .= "$field $dir, ";
  713. }
  714. $sql = drupal_substr($sql, 0, -2); // get rid of the trailing ', '
  715. }
  716. // if the caller has requested the SQL rather than the results...
  717. // which happens in the case of wanting to use the Drupal pager, then do so
  718. if ($options['return_sql']) {
  719. return array('sql' => $sql, 'args' => $args);
  720. }
  721. $previous_db = tripal_db_set_active('chado'); // use chado database
  722. $resource = db_query($sql, $args);
  723. tripal_db_set_active($previous_db); // now use drupal database
  724. $results = array();
  725. while ($r = db_fetch_object($resource)) {
  726. $results[] = $r;
  727. }
  728. if (!$options['has_record']) {
  729. return $results;
  730. }
  731. else {
  732. return count($results);
  733. }
  734. }
  735. /**
  736. * Gets the value of a foreign key relationship
  737. *
  738. * This function is used by tripal_core_chado_select, tripal_core_chado_insert,
  739. * and tripal_core_chado_update to iterate through the associate array of
  740. * values that gets passed to each of those routines. The values array
  741. * is nested where foreign key contraints are used to specify a value that. See
  742. * documentation for any of those functions for further information.
  743. *
  744. * @param $table_desc
  745. * A table description for the table with the foreign key relationship to be identified generated by
  746. * hook_chado_<table name>_schema()
  747. * @param $field
  748. * The field in the table that is the foreign key.
  749. * @param $values
  750. * An associative array containing the values
  751. * @param $options
  752. * An associative array of additional options where the key is the option
  753. * and the value is the value of that option. These options are passed on to tripal_core_chado_select.
  754. *
  755. * Additional Options Include:
  756. * - case_insensitive_columns
  757. * An array of columns to do a case insensitive search on.
  758. * - regex_columns
  759. * An array of columns where the value passed in should be treated as a regular expression
  760. *
  761. * @return
  762. * A string containg the results of the foreign key lookup, or FALSE if failed.
  763. *
  764. * Example usage:
  765. * @code
  766. *
  767. * $values = array(
  768. * 'genus' => 'Citrus',
  769. * 'species' => 'sinensis',
  770. * );
  771. * $value = tripal_core_chado_get_foreign_key('feature', 'organism_id',$values);
  772. *
  773. * @endcode
  774. * The above code selects a record from the feature table using the three fields
  775. * that uniquely identify a feature. The $columns array simply lists the columns
  776. * to select. The $values array is nested such that the organism is identified by
  777. * way of the organism_id foreign key constraint by specifying the genus and
  778. * species. The cvterm is also specified using its foreign key and the cv_id
  779. * for the cvterm is nested as well.
  780. *
  781. * @ingroup tripal_chado_api
  782. */
  783. function tripal_core_chado_get_foreign_key($table_desc, $field, $values, $options = NULL) {
  784. if (!is_array($options)) {
  785. $options = array();
  786. }
  787. if (!$options['case_insensitive_columns']) {
  788. $options['case_insensitive_columns'] = array();
  789. }
  790. if (!$options['regex_columns']) {
  791. $options['regex_columns'] = array();
  792. }
  793. // get the list of foreign keys for this table description and
  794. // iterate through those until we find the one we're looking for
  795. $fkeys = $table_desc['foreign keys'];
  796. if ($fkeys) {
  797. foreach ($fkeys as $name => $def) {
  798. if (is_array($def['table'])) {
  799. //foreign key was described 2X
  800. $message = "The foreign key " . $name . " was defined twice. Please check modules "
  801. ."to determine if hook_chado_" . $table_desc['table'] . "_schema() was "
  802. ."implemented and defined this foreign key when it wasn't supposed to. Modules "
  803. ."this hook was implemented in: " . implode(', ',
  804. module_implements("chado_" . $table_desc['table'] . "_schema")) . ".";
  805. watchdog('tripal_core', $message);
  806. drupal_set_message(check_plain($message), 'error');
  807. continue;
  808. }
  809. $table = $def['table'];
  810. $columns = $def['columns'];
  811. // iterate through the columns of the foreign key relationship
  812. foreach ($columns as $left => $right) {
  813. // does the left column in the relationship match our field?
  814. if (strcmp($field, $left) == 0) {
  815. // the column name of the foreign key matches the field we want
  816. // so this is the right relationship. Now we want to select
  817. $select_cols = array($right);
  818. $result = tripal_core_chado_select($table, $select_cols, $values, $options);
  819. $fields = array();
  820. if (count($result) > 0) {
  821. foreach ($result as $obj) {
  822. $fields[] = $obj->$right;
  823. }
  824. return $fields;
  825. }
  826. }
  827. }
  828. }
  829. }
  830. else {
  831. // TODO: what do we do if we get to this point and we have a fk
  832. // relationship expected but we don't have any definition for one in the
  833. // table schema??
  834. $message = "There is no foreign key relationship defined for " . $field . ".
  835. To define a foreign key relationship, determine the table this foreign
  836. key referrs to (<foreign table>) and then implement
  837. hook_chado_<foreign table>_schema(). See
  838. tripal_feature_chado_feature_schema for an example.";
  839. watchdog('tripal_core', $message);
  840. drupal_set_message(check_plain($message), 'error');
  841. }
  842. return FALSE;
  843. }
  844. /**
  845. * Generates an object containing the full details of a record(s) in chado.
  846. *
  847. * This differs from the objects returned by tripal_core_chado_select in so far as all foreign key
  848. * relationships have been followed meaning you have more complete details. Thus this function
  849. * should be used whenever you need a full variable and tripal_core_chado_select should be used if
  850. * you only case about a few columns.
  851. *
  852. * @param $table
  853. * The name of the base table to generate a variable for
  854. * @param $values
  855. * A select values array that selects the records you want from the base table
  856. * (this has the same form as tripal_core_chado_select)
  857. * @param $base_options
  858. * An array containing options for the base table. For example, an
  859. * option of 'order_by' may be used to sort results in the base table
  860. * if more than one are returned. The options must be compatible with
  861. * the options accepted by the tripal_core_chado_select() function.
  862. * @return
  863. * Either an object (if only one record was selected from the base table)
  864. * or an array of objects (if more than one record was selected from the base table).
  865. *
  866. * Example Usage:
  867. * @code
  868. $values = array(
  869. 'name' => 'Medtr4g030710'
  870. );
  871. $features = tripal_core_generate_chado_var('feature', $values);
  872. * @endcode
  873. * This will return an object if there is only one feature with the name Medtr4g030710 or it will
  874. * return an array of feature objects if more than one feature has that name.
  875. *
  876. * Note to Module Designers: Fields can be excluded by default from these objects by implementing
  877. * one of the following hooks:
  878. * - hook_exclude_field_from_tablename_by_default (where tablename is the name of the table):
  879. * This hook allows you to add fields to be excluded on a per table basis. Simply implement
  880. * this hook to return an array of fields to be excluded. For example:
  881. * @code
  882. mymodule_exclude_field_from_feature_by_default() {
  883. return array('residues' => TRUE);
  884. }
  885. * @endcode
  886. * will ensure that feature.residues is ecluded from a feature object by default.
  887. * - hook_exclude_type_by_default:
  888. * This hook allows you to exclude fields from all tables that are of a given postgresql field
  889. * type. Simply implement this hook to return an array of postgresql types mapped to criteria.
  890. * Then all fields of that type where the criteria supplied returns TRUE will be excluded from
  891. * any table. Tokens available in criteria are &gt;field_value&lt; and &gt;field_name&lt; . For example:
  892. * @code
  893. mymodule_exclude_type_by_default() {
  894. return array('text' => 'length(&gt;field_value&lt; ) > 50');
  895. }
  896. * @endcode
  897. * 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.
  898. *
  899. * @ingroup tripal_chado_api
  900. */
  901. function tripal_core_generate_chado_var($table, $values, $base_options = array()) {
  902. $all = new stdClass();
  903. // get description for the current table----------------------------------------------------------
  904. $table_desc = module_invoke_all('chado_' . $table . '_schema');
  905. $table_primary_key = $table_desc['primary key'][0];
  906. $table_columns = array_keys($table_desc['fields']);
  907. // Expandable fields without value needed for criteria--------------------------------------------
  908. $all->expandable_fields = array();
  909. if ($table_desc['referring_tables']) {
  910. $all->expandable_tables = $table_desc['referring_tables'];
  911. }
  912. else {
  913. $all->expandable_tables = array();
  914. }
  915. $all->expandable_nodes = array();
  916. // Get fields to be removed by name.................................
  917. $fields_to_remove = module_invoke_all('exclude_field_from_' . $table . '_by_default');
  918. foreach ($fields_to_remove as $field_name => $criteria) {
  919. //replace &gt;field_name&lt; with the current field name &
  920. $criteria = preg_replace('/&gt;field_name&lt; /', $field_name, $criteria);
  921. // if field_value needed we can't deal with this field yet
  922. if (preg_match('/&gt;field_value&lt; /', $criteria)) {
  923. break;
  924. }
  925. //if criteria then remove from query
  926. $success = drupal_eval('<?php return ' . $criteria . '; ?>');
  927. // watchdog('tripal_core',
  928. // 'Evaluating criteria (%criteria) for field %field in tripal_core_generate_chado_var for %table evaluated to %success',
  929. // array('%table' => $table, '%criteria'=>$criteria, '%field' => $field_name, '%success'=>$success),
  930. // WATCHDOG_NOTICE
  931. // );
  932. if ($success) {
  933. unset($table_columns[array_search($field_name, $table_columns)]);
  934. unset($fields_to_remove[$field_name]);
  935. $all->expandable_fields[] = $table . '.' . $field_name;
  936. }
  937. }
  938. //Get fields to be removed by type................................
  939. $types_to_remove = module_invoke_all('exclude_type_by_default');
  940. $field_types = array();
  941. foreach ($table_desc['fields'] as $field_name => $field_array) {
  942. $field_types[$field_array['type']][] = $field_name;
  943. }
  944. foreach ($types_to_remove as $field_type => $criteria) {
  945. // if there are fields of that type to remove
  946. if (is_array($field_types[$field_type])) {
  947. //replace &gt;field_name&lt; with the current field name &
  948. $criteria = preg_replace('/&gt;field_name&lt; /', $field_name, $criteria);
  949. foreach ($field_types[$field_type] as $field_name) {
  950. // if field_value needed we can't deal with this field yet
  951. if (preg_match('/&gt;field_value&lt; /', $criteria)) {
  952. $fields_to_remove[$field_name] = $criteria;
  953. continue;
  954. }
  955. // if field_value needed we can't deal with this field yet
  956. if (preg_match('/&gt;field_value&lt; /', $criteria)) {
  957. break;
  958. }
  959. //if criteria then remove from query
  960. $success = drupal_eval('<?php return ' . $criteria . '; ?>');
  961. // watchdog('tripal_core',
  962. // 'Evaluating criteria (%criteria) for field %field of $type in tripal_core_generate_chado_var for %table evaluated to %success',
  963. // array('%table'=>$table, '%criteria'=>$criteria, '%field'=>$field_name, '%type'=>$field_type, '%success'=>$success),
  964. // WATCHDOG_NOTICE
  965. // );
  966. if ($success) {
  967. unset($table_columns[array_search($field_name, $table_columns)]);
  968. $all->expandable_fields[] = $table . '.' . $field_name;
  969. }
  970. } //end of foreach field of that type
  971. }
  972. } //end of foreach type to be removed
  973. // get the values for the record in the current table---------------------------------------------
  974. $results = tripal_core_chado_select($table, $table_columns, $values, $base_options);
  975. if ($results) {
  976. foreach ($results as $key => $object) {
  977. // Add empty expandable_x arrays
  978. $object->expandable_fields = $all->expandable_fields;
  979. $object->expandable_tables = $all->expandable_tables;
  980. $object->expandable_nodes = $all->expandable_nodes;
  981. // add curent table
  982. $object->tablename = $table;
  983. // check if the current table maps to a node type-----------------------------------------------
  984. // if this table is connected to a node there will be a chado_tablename table in drupal
  985. if (db_table_exists('chado_' . $table)) {
  986. // that has a foreign key to this one ($table_desc['primary key'][0]
  987. // and to the node table (nid)
  988. $sql = "SELECT %s, nid FROM chado_%s WHERE %s=%d";
  989. $mapping = db_fetch_object(db_query(
  990. $sql,
  991. $table_primary_key,
  992. $table,
  993. $table_primary_key,
  994. $object->{$table_primary_key}
  995. ));
  996. if ($mapping->{$table_primary_key}) {
  997. $object->nid = $mapping->nid;
  998. $object->expandable_nodes[] = $table;
  999. }
  1000. }
  1001. // remove any fields where criteria need to be evalulated---------------------------------------
  1002. foreach ($fields_to_remove as $field_name => $criteria) {
  1003. if (!isset($object->{$field_name})) {
  1004. break;
  1005. }
  1006. $criteria = preg_replace('/&gt;field_value&lt; /', $object->{$field_name}, $criteria);
  1007. //if criteria then remove from query
  1008. $success = drupal_eval('<?php return ' . $criteria . '; ?>');
  1009. // watchdog('tripal_core',
  1010. // 'Evaluating criteria (%criteria) for field %field in tripal_core_generate_chado_var for %table evaluated to %success',
  1011. // array('%table' => $table, '%criteria'=>$criteria, '%field' => $field_name, '%success'=>$success),
  1012. // WATCHDOG_NOTICE
  1013. // );
  1014. if ($success) {
  1015. unset($object->{$field_name});
  1016. $object->expandable_fields[] = $table . '.' . $field_name;
  1017. }
  1018. }
  1019. // recursively follow foreign key relationships nesting objects as we go------------------------
  1020. if ($table_desc['foreign keys']) {
  1021. foreach ($table_desc['foreign keys'] as $foreign_key_array) {
  1022. $foreign_table = $foreign_key_array['table'];
  1023. foreach ($foreign_key_array['columns'] as $foreign_key => $primary_key) {
  1024. // Note: Foreign key is the field in the current table whereas primary_key is the field in
  1025. // the table referenced by the foreign key
  1026. //Dont do anything if the foreign key is empty
  1027. if (empty($object->{$foreign_key})) {
  1028. break;
  1029. }
  1030. // get the record from the foreign table
  1031. $foreign_values = array($primary_key => $object->{$foreign_key});
  1032. $foreign_object = tripal_core_generate_chado_var($foreign_table, $foreign_values);
  1033. // add the foreign record to the current object in a nested manner
  1034. $object->{$foreign_key} = $foreign_object;
  1035. // Flatten expandable_x arrays so only in the bottom object
  1036. if (is_array($object->{$foreign_key}->expandable_fields)) {
  1037. $object->expandable_fields = array_merge(
  1038. $object->expandable_fields,
  1039. $object->{$foreign_key}->expandable_fields
  1040. );
  1041. unset($object->{$foreign_key}->expandable_fields);
  1042. }
  1043. if (is_array($object->{$foreign_key}->expandable_tables)) {
  1044. $object->expandable_tables = array_merge(
  1045. $object->expandable_tables,
  1046. $object->{$foreign_key}->expandable_tables
  1047. );
  1048. unset($object->{$foreign_key}->expandable_tables);
  1049. }
  1050. if (is_array($object->{$foreign_key}->expandable_nodes)) {
  1051. $object->expandable_nodes = array_merge(
  1052. $object->expandable_nodes,
  1053. $object->{$foreign_key}->expandable_nodes
  1054. );
  1055. unset($object->{$foreign_key}->expandable_nodes);
  1056. }
  1057. }
  1058. }
  1059. $results[$key] = $object;
  1060. }
  1061. }
  1062. }
  1063. // check only one result returned
  1064. if (sizeof($results) == 1) {
  1065. // add results to object
  1066. return $results[0];
  1067. }
  1068. elseif (!empty($results)) {
  1069. return $results;
  1070. }
  1071. else {
  1072. // no results returned
  1073. }
  1074. }
  1075. /**
  1076. * Retrieves fields/tables/nodes that were excluded by default from a variable and adds them
  1077. *
  1078. * This function exists to allow tripal_core_generate_chado_var() to excldue some
  1079. * fields/tables/nodes from the default form of a variable without making it extremely difficult for
  1080. * the tripal admin to get at these variables if he/she wants them.
  1081. *
  1082. * @param $object
  1083. * This must be an object generated using tripal_core_generate_chado_var()
  1084. * @param $type
  1085. * Must be one of 'field', 'table', 'node'. Indicates what is being expanded.
  1086. * @param $to_expand
  1087. * The name of the field/table/node to be expanded
  1088. * @param $table_options
  1089. * An array containing options for the base table. For example, an
  1090. * option of 'order_by' may be used to sort results in the base table
  1091. * if more than one are returned. The options must be compatible with
  1092. * the options accepted by the tripal_core_chado_select() function.
  1093. * @return
  1094. * A chado object supplemented with the field/table/node requested to be expanded
  1095. *
  1096. * Example Usage:
  1097. * @code
  1098. // Get a chado object to be expanded
  1099. $values = array(
  1100. 'name' => 'Medtr4g030710'
  1101. );
  1102. $features = tripal_core_generate_chado_var('feature', $values);
  1103. // Expand the organism node
  1104. $feature = tripal_core_expand_chado_vars($feature, 'node', 'organism');
  1105. // Expand the feature.residues field
  1106. $feature = tripal_core_expand_chado_vars($feature, 'field', 'feature.residues');
  1107. // Expand the feature properties (featureprop table)
  1108. $feature = tripal_core_expand_chado_vars($feature, 'table', 'featureprop');
  1109. * @endcode
  1110. *
  1111. * @ingroup tripal_chado_api
  1112. */
  1113. function tripal_core_expand_chado_vars($object, $type, $to_expand, $table_options = array()) {
  1114. $base_table = $object->tablename;
  1115. // check to see if they are expanding an array of objects
  1116. if (is_array($object)) {
  1117. foreach ($object as $index => $o) {
  1118. $object[$index] = tripal_core_expand_chado_vars($o, $type, $to_expand);
  1119. }
  1120. return $object;
  1121. }
  1122. switch ($type) {
  1123. case "field": //--------------------------------------------------------------------------------
  1124. if (preg_match('/(\w+)\.(\w+)/', $to_expand, $matches)) {
  1125. $tablename = $matches[1];
  1126. $fieldname = $matches[2];
  1127. $table_desc = module_invoke_all('chado_' . $tablename . '_schema');
  1128. $values = array();
  1129. foreach ($table_desc['primary key'] as $key) {
  1130. $values[$key] = $object->{$key};
  1131. }
  1132. if ($base_table == $tablename) {
  1133. //get the field
  1134. $results = tripal_core_chado_select(
  1135. $tablename,
  1136. array($fieldname),
  1137. $values
  1138. );
  1139. $object->{$fieldname} = $results[0]->{$fieldname};
  1140. $object->expanded = $to_expand;
  1141. }
  1142. else {
  1143. //We need to recurse -the field is in a nested object
  1144. foreach ((array) $object as $field_name => $field_value) {
  1145. if (is_object($field_value)) {
  1146. $object->{$field_name} = tripal_core_expand_chado_vars(
  1147. $field_value,
  1148. 'field',
  1149. $to_expand
  1150. );
  1151. }
  1152. } //end of for each field in the current object
  1153. }
  1154. }
  1155. else {
  1156. watchdog(
  1157. 'tripal_core',
  1158. 'tripal_core_expand_chado_vars: Field (%field) not in the right format. It should be <tablename>.<fieldname>',
  1159. WATCHDOG_ERROR
  1160. );
  1161. }
  1162. break;
  1163. case "table": //--------------------------------------------------------------------------------
  1164. $foreign_table = $to_expand;
  1165. $foreign_table_desc = module_invoke_all('chado_' . $foreign_table . '_schema');
  1166. // If it's connected to the base table
  1167. if ($foreign_table_desc['foreign keys'][$base_table]) {
  1168. foreach ($foreign_table_desc['foreign keys'][$base_table]['columns'] as $left => $right) {
  1169. if (!$object->{$right}) {
  1170. break;
  1171. }
  1172. if (is_array($values)) {
  1173. $values = array_merge($values, array($left => $object->{$right}) );
  1174. }
  1175. else {
  1176. $values = array($left => $object->{$right});
  1177. }
  1178. $foreign_object = tripal_core_generate_chado_var(
  1179. $foreign_table,
  1180. array($left => $object->{$right}),
  1181. $table_options
  1182. );
  1183. if ($foreign_object) {
  1184. // in the case where the a foreign key relationships exists more
  1185. // than once with the same table we want to alter the
  1186. // array structure
  1187. if (count($foreign_table_desc['foreign keys'][$base_table]['columns']) > 1) {
  1188. $object->{$foreign_table}->{$left} = $foreign_object;
  1189. $object->expanded = $to_expand;
  1190. }
  1191. else {
  1192. $object->{$foreign_table} = $foreign_object;
  1193. $object->expanded = $to_expand;
  1194. }
  1195. }
  1196. }
  1197. }
  1198. else {
  1199. //We need to recurse -the table has a relationship to one of the nested objects
  1200. foreach ((array) $object as $field_name => $field_value) {
  1201. // if we have a nested object ->expand the table in it
  1202. if (is_object($field_value)) {
  1203. $object->{$field_name} = tripal_core_expand_chado_vars(
  1204. $field_value,
  1205. 'table',
  1206. $foreign_table
  1207. );
  1208. }
  1209. }
  1210. }
  1211. break;
  1212. case "node": //---------------------------------------------------------------------------------
  1213. //if the node to be expanded is for our base table, then just expand it
  1214. if ($object->tablename == $to_expand) {
  1215. $node = node_load($object->nid);
  1216. if ($node) {
  1217. $object->expanded = $to_expand;
  1218. $node->expandable_fields = $object->expandable_fields;
  1219. unset($object->expandable_fields);
  1220. $node->expandable_tables = $object->expandable_tables;
  1221. unset($object->expandable_tables);
  1222. $node->expandable_nodes = $object->expandable_nodes;
  1223. unset($object->expandable_nodes);
  1224. $node->{$base_table} = $object;
  1225. $object = $node;
  1226. }
  1227. else {
  1228. watchdog(
  1229. 'tripal_core',
  1230. 'tripal_core_expand_chado_vars: No node matches the nid (%nid) supplied.',
  1231. array('%nid' => $object->nid),
  1232. WATCHDOG_ERROR
  1233. );
  1234. } //end of if node
  1235. }
  1236. else {
  1237. //We need to recurse -the node to expand is one of the nested objects
  1238. foreach ((array) $object as $field_name => $field_value) {
  1239. if (is_object($field_value)) {
  1240. $object->{$field_name} = tripal_core_expand_chado_vars(
  1241. $field_value,
  1242. 'node',
  1243. $to_expand
  1244. );
  1245. }
  1246. } //end of for each field in the current object
  1247. }
  1248. break;
  1249. default:
  1250. watchdog('tripal_core',
  1251. 'tripal_core_expand_chado_vars: Unrecognized type (%type). Should be one of "field", "table", "node".',
  1252. array('%type' => $type),
  1253. WATCHDOG_ERROR
  1254. );
  1255. return FALSE;
  1256. }
  1257. //move extended array downwards-------------------------------------------------------------------
  1258. if (!$object->expanded) {
  1259. //if there's no extended field then go hunting for it
  1260. foreach ( (array)$object as $field_name => $field_value) {
  1261. if (is_object($field_value)) {
  1262. if (isset($field_value->expanded)) {
  1263. $object->expanded = $field_value->expanded;
  1264. unset($field_value->expanded);
  1265. }
  1266. }
  1267. }
  1268. }
  1269. //try again becasue now we might have moved it down
  1270. if ($object->expanded) {
  1271. $expandable_name = 'expandable_' . $type . 's';
  1272. if ($object->{$expandable_name}) {
  1273. $key_to_remove = array_search($object->expanded, $object->{$expandable_name});
  1274. unset($object->{$expandable_name}[$key_to_remove]);
  1275. unset($object->expanded);
  1276. }
  1277. else {
  1278. // if there is an expandable array then we've reached the base object
  1279. // if we get here and don't have anything expanded then something went wrong
  1280. // watchdog(
  1281. // 'tripal_core',
  1282. // 'tripal_core_expand_chado_vars: Unable to expand the %type %to_expand',
  1283. // array('%type'=>$type, '%to_expand'=>$to_expand),
  1284. // WATCHDOG_ERROR
  1285. // );
  1286. } //end of it we've reached the base object
  1287. }
  1288. return $object;
  1289. }
  1290. /**
  1291. * Implements hook_exclude_type_by_default()
  1292. *
  1293. * This hooks allows fields of a specified type that match a specified criteria to be excluded by
  1294. * default from any table when tripal_core_generate_chado_var() is called. Keep in mind that if
  1295. * fields are excluded by default they can always be expanded at a later date using
  1296. * tripal_core_expand_chado_vars().
  1297. *
  1298. * Criteria are php strings that evaluate to either TRUE or FALSE. These strings are evaluated using
  1299. * drupal_eval() which suppresses syntax errors and throws watchdog entries of type php. There are
  1300. * also watchdog entries of type tripal_core stating the exact criteria evaluated. Criteria can
  1301. * contain the following tokens:
  1302. * - &gt;field_name&lt;
  1303. * Replaced by the name of the field to be excluded
  1304. * - &gt;field_value&lt;
  1305. * Replaced by the value of the field in the current record
  1306. * Also keep in mind that if your criteria doesn't contain the &gt;field_value&lt; token then it will be
  1307. * evaluated before the query is executed and if the field is excluded it won't be included in the
  1308. * query.
  1309. *
  1310. * @return
  1311. * An array of type => criteria where the type is excluded if the criteria evaluates to TRUE
  1312. *
  1313. * @ingroup tripal_chado_api
  1314. */
  1315. function tripal_core_exclude_type_by_default() {
  1316. return array('text' => "strlen('&gt;field_value&lt; ') > 100");
  1317. }
  1318. /**
  1319. * Implements hook_exclude_field_from_<tablename>_by_default()
  1320. *
  1321. * This hooks allows fields from a specified table that match a specified criteria to be excluded by
  1322. * default from any table when tripal_core_generate_chado_var() is called. Keep in mind that if
  1323. * fields are excluded by default they can always be expanded at a later date using
  1324. * tripal_core_expand_chado_vars().
  1325. *
  1326. * Criteria are php strings that evaluate to either TRUE or FALSE. These strings are evaluated using
  1327. * drupal_eval() which suppresses syntax errors and throws watchdog entries of type php. There are
  1328. * also watchdog entries of type tripal_core stating the exact criteria evaluated. Criteria can
  1329. * contain the following tokens:
  1330. * - &gt;field_name&lt;
  1331. * Replaced by the name of the field to be excluded
  1332. * - &gt;field_value&lt;
  1333. * Replaced by the value of the field in the current record
  1334. * Also keep in mind that if your criteria doesn't contain the &gt;field_value&lt; token then it will be
  1335. * evaluated before the query is executed and if the field is excluded it won't be included in the
  1336. * query.
  1337. *
  1338. * @return
  1339. * An array of type => criteria where the type is excluded if the criteria evaluates to TRUE
  1340. *
  1341. * @ingroup tripal_chado_api
  1342. */
  1343. function tripal_core_exclude_field_from_feature_by_default() {
  1344. return array();
  1345. }
  1346. /**
  1347. * Use this function instead of db_query() to avoid switching databases
  1348. * when making query to the chado database
  1349. *
  1350. * Will use a chado persistent connection if it already exists
  1351. *
  1352. * @param $sql
  1353. * The sql statement to execute
  1354. */
  1355. function chado_query($sql) {
  1356. global $active_db;
  1357. $args = func_get_args();
  1358. array_shift($args);
  1359. $sql = db_prefix_tables($sql);
  1360. if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
  1361. $args = $args[0];
  1362. }
  1363. _db_query_callback($args, TRUE);
  1364. $sql = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $sql);
  1365. // Execute the query on the chado database/schema
  1366. // Use the persistent chado connection if it already exists
  1367. $persistent_connection = variable_get('tripal_perisistent_chado',NULL);
  1368. if ($persistent_connection) {
  1369. $previously_active_db = $active_db;
  1370. $active_db = $persistent_connection;
  1371. $results = _db_query($sql);
  1372. $active_db = $previously_active_db;
  1373. }
  1374. else {
  1375. $previous_db = tripal_db_set_active('chado');
  1376. $results = _db_query($sql);
  1377. tripal_db_set_active($previous_db);
  1378. }
  1379. return $results;
  1380. }
  1381. /**
  1382. * Get chado id for a node. E.g, if you want to get 'analysis_id' from the
  1383. * 'analysis' table for a synced 'chado_analysis' node, use:
  1384. * $analysis_id = chado_get_id_for_node ('analysis', $node)
  1385. * Likewise,
  1386. * $organism_id = chado_get_id_for_node ('organism', $node)
  1387. * $feature_id = chado_get_id_for_node ('feature', $node)
  1388. */
  1389. function chado_get_id_for_node($table, $node) {
  1390. return db_result(db_query("SELECT %s_id FROM {chado_%s} WHERE nid = %d", $table, $table, $node->nid));
  1391. }
  1392. /**
  1393. * Get node id for a chado feature/organism/analysis. E.g, if you want to
  1394. * get the node id for an analysis, use:
  1395. * $nid = chado_get_node_id ('analysis', $analysis_id)
  1396. * Likewise,
  1397. * $nid = chado_get_node_id ('organism', $organism_id)
  1398. * $nid = chado_get_node_id ('feature', $feature_id)
  1399. */
  1400. function chado_get_node_id($table, $id) {
  1401. return db_result(db_query("SELECT nid FROM {chado_%s} WHERE %s_id = %d", $table, $table, $id));
  1402. }
  1403. /**
  1404. * Retrieve a property for a given base table record
  1405. *
  1406. * @param $basetable
  1407. * The base table for which the property should be retrieved. Thus to retrieve a property
  1408. * for a feature the basetable=feature and property is retrieved from featureprop
  1409. * @param $record_id
  1410. * The foriegn key field of the base table. This should be in integer.
  1411. * @param $property
  1412. * The cvterm name describing the type of properties to be retrieved
  1413. * @param $cv_name
  1414. * The name of the cv that the above cvterm is part of
  1415. *
  1416. * @return
  1417. * An array in the same format as that generated by the function
  1418. * tripal_core_generate_chado_var(). If only one record is returned it
  1419. * is a single object. If more than one record is returned then it is an array
  1420. * of objects
  1421. *
  1422. * @ingroup tripal_chado_api
  1423. */
  1424. function tripal_core_get_property($basetable, $record_id, $property, $cv_name) {
  1425. // get the foreign key for this property table
  1426. $table_desc = module_invoke_all('chado_' . $basetable . 'prop_schema');
  1427. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1428. // construct the array of values to be selected
  1429. $values = array(
  1430. $fkcol => $record_id,
  1431. 'type_id' => array(
  1432. 'cv_id' => array(
  1433. 'name' => $cv_name,
  1434. ),
  1435. 'name' => $property,
  1436. 'is_obsolete' => 0
  1437. ),
  1438. );
  1439. $results = tripal_core_generate_chado_var($basetable . 'prop', $values);
  1440. $results = tripal_core_expand_chado_vars($results, 'field', $basetable . 'prop.value');
  1441. return $results;
  1442. }
  1443. /**
  1444. * Insert a property for a given base table. By default if the property already
  1445. * exists a new property is added with the next available rank. If
  1446. * $update_if_present argument is specified then the record will be updated if it
  1447. * exists rather than adding a new property.
  1448. *
  1449. * @param $basetable
  1450. * The base table for which the property should be inserted. Thus to insert a property
  1451. * for a feature the basetable=feature and property is inserted into featureprop
  1452. * @param $record_id
  1453. * The foriegn key field of the base table. This should be in integer.
  1454. * @param $property
  1455. * The cvterm name describing the type of properties to be inserted
  1456. * @param $cv_name
  1457. * The name of the cv that the above cvterm is part of
  1458. * @param $value
  1459. * The value of the property to be inserted (can be empty)
  1460. * @param $update_if_present
  1461. * A boolean indicating whether an existing record should be updated. If the
  1462. * property already exists and this value is not specified or is zero then
  1463. * a new property will be added with the next largest rank.
  1464. *
  1465. * @return
  1466. * Return True on Insert/Update and False otherwise
  1467. *
  1468. * @ingroup tripal_chado_api
  1469. */
  1470. function tripal_core_insert_property($basetable, $record_id, $property,
  1471. $cv_name, $value, $update_if_present = 0) {
  1472. // first see if the property already exists, if the user want's to update
  1473. // then we can do that, but otherwise we want to increment the rank and
  1474. // insert
  1475. $props = tripal_core_get_property($basetable, $record_id, $property, $cv_name);
  1476. if (!is_array($props)) {
  1477. $props = array($props);
  1478. }
  1479. $rank = 0;
  1480. if (count($props)>0) {
  1481. if ($update_if_present) {
  1482. return tripal_core_update_property($basetable, $record_id, $property, $cv_name, $value);
  1483. }
  1484. else {
  1485. // iterate through the properties returned and check to see if the
  1486. // property with this value already exists if not, get the largest rank
  1487. // and insert the same property but with this new value
  1488. foreach ($props as $p) {
  1489. if ($p->rank > $rank) {
  1490. $rank = $p->rank;
  1491. }
  1492. if (strcmp($p->value, $value) == 0) {
  1493. return TRUE;
  1494. }
  1495. }
  1496. // now add 1 to the rank
  1497. $rank++;
  1498. }
  1499. }
  1500. // get the foreign key for this property table
  1501. $table_desc = module_invoke_all('chado_' . $basetable . 'prop_schema');
  1502. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1503. // construct the array of values to be inserted
  1504. $values = array(
  1505. $fkcol => $record_id,
  1506. 'type_id' => array(
  1507. 'cv_id' => array(
  1508. 'name' => $cv_name,
  1509. ),
  1510. 'name' => $property,
  1511. 'is_obsolete' => 0
  1512. ),
  1513. 'value' => $value,
  1514. 'rank' => $rank,
  1515. );
  1516. return tripal_core_chado_insert($basetable . 'prop', $values);
  1517. }
  1518. /**
  1519. * Update a property for a given base table record and property name. This
  1520. * function should be used only if one record of the property will be present.
  1521. * If the property name can have multiple entries (with increasing rank) then
  1522. * use the function named tripal_core_update_property_by_id
  1523. *
  1524. * @param $basetable
  1525. * The base table for which the property should be updated. The property table
  1526. * is constructed using a combination of the base table name and the suffix
  1527. * 'prop' (e.g. basetable = feature then property tabie is featureprop).
  1528. * @param $record_id
  1529. * The foreign key of the basetable to update a property for. This should be in integer.
  1530. * For example, if the basetable is 'feature' then the $record_id should be the feature_id
  1531. * @param $property
  1532. * The cvterm name of property to be updated
  1533. * @param $cv_name
  1534. * The name of the cv that the above cvterm is part of
  1535. * @param $value
  1536. * The value of the property to be inserted (can be empty)
  1537. * @param $insert_if_missing
  1538. * A boolean indicating whether a record should be inserted if one doesn't exist to update
  1539. *
  1540. * Note: The property to be updated is select via the unique combination of $record_id and
  1541. * $property and then it is updated with the supplied value
  1542. *
  1543. * @return
  1544. * Return True on Update/Insert and False otherwise
  1545. *
  1546. * @ingroup tripal_chado_api
  1547. */
  1548. function tripal_core_update_property($basetable, $record_id, $property,
  1549. $cv_name, $value, $insert_if_missing = 0) {
  1550. // first see if the property is missing (we can't update a missing property
  1551. $prop = tripal_core_get_property($basetable, $record_id, $property, $cv_name);
  1552. if (count($prop)==0) {
  1553. if ($insert_if_missing) {
  1554. return tripal_core_insert_property($basetable, $record_id, $property, $cv_name, $value);
  1555. }
  1556. else {
  1557. return FALSE;
  1558. }
  1559. }
  1560. // get the foreign key for this property table
  1561. $table_desc = module_invoke_all('chado_' . $basetable . 'prop_schema');
  1562. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1563. // construct the array that will match the exact record to update
  1564. $match = array(
  1565. $fkcol => $record_id,
  1566. 'type_id' => array(
  1567. 'cv_id' => array(
  1568. 'name' => $cv_name,
  1569. ),
  1570. 'name' => $property,
  1571. ),
  1572. );
  1573. // construct the array of values to be updated
  1574. $values = array(
  1575. 'value' => $value,
  1576. );
  1577. return tripal_core_chado_update($basetable . 'prop', $match, $values);
  1578. }
  1579. /**
  1580. * Update a property for a given base table record. This function should be
  1581. * used if multiple records of the same property will be present. Also, use this
  1582. * function to change the property name of an existing property.
  1583. *
  1584. * @param $basetable
  1585. * The base table for which the property should be updated. The property table
  1586. * is constructed using a combination of the base table name and the suffix
  1587. * 'prop' (e.g. basetable = feature then property tabie is featureprop).
  1588. * @param $record_id
  1589. * The primary key of the base table. This should be in integer.
  1590. * For example, if the basetable is 'feature' then the $record_id should be the featureprop_id
  1591. * @param $property
  1592. * The cvterm name of property to be updated
  1593. * @param $cv_name
  1594. * The name of the cv that the above cvterm is part of
  1595. * @param $value
  1596. * The value of the property to be inserted (can be empty)
  1597. *
  1598. * @return
  1599. * Return True on Update/Insert and False otherwise
  1600. *
  1601. * @ingroup tripal_chado_api
  1602. */
  1603. function tripal_core_update_property_by_id($basetable, $record_id, $property,
  1604. $cv_name, $value) {
  1605. // get the primary key for this property table
  1606. $table_desc = module_invoke_all('chado_' . $basetable . 'prop_schema');
  1607. $pkcol = $table_desc['primary key'][0];
  1608. // construct the array that will match the exact record to update
  1609. $match = array(
  1610. $pkcol => $record_id,
  1611. );
  1612. // construct the array of values to be updated
  1613. $values = array(
  1614. 'type_id' => array(
  1615. 'cv_id' => array(
  1616. 'name' => $cv_name,
  1617. ),
  1618. 'name' => $property,
  1619. ),
  1620. 'value' => $value,
  1621. );
  1622. return tripal_core_chado_update($basetable . 'prop', $match, $values);
  1623. }
  1624. /**
  1625. * Deletes a property for a given base table record using the property name
  1626. *
  1627. * @param $basetable
  1628. * The base table for which the property should be deleted. Thus to deleted a property
  1629. * for a feature the basetable=feature and property is deleted from featureprop
  1630. * @param $record_id
  1631. * The primary key of the basetable to delete a property for. This should be in integer.
  1632. * @param $property
  1633. * The cvterm name describing the type of property to be deleted
  1634. * @param $cv_name
  1635. * The name of the cv that the above cvterm is part of
  1636. *
  1637. * Note: The property to be deleted is select via the unique combination of $record_id and $property
  1638. *
  1639. * @return
  1640. * Return True on Delete and False otherwise
  1641. *
  1642. * @ingroup tripal_chado_api
  1643. */
  1644. function tripal_core_delete_property($basetable, $record_id, $property, $cv_name) {
  1645. // get the foreign key for this property table
  1646. $table_desc = module_invoke_all('chado_' . $basetable . 'prop_schema');
  1647. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1648. // construct the array that will match the exact record to update
  1649. $match = array(
  1650. $fkcol => $record_id,
  1651. 'type_id' => array(
  1652. 'cv_id' => array(
  1653. 'name' => $cv_name,
  1654. ),
  1655. 'name' => $property,
  1656. ),
  1657. );
  1658. return tripal_core_chado_delete($basetable . 'prop', $match);
  1659. }
  1660. /**
  1661. * Deletes a property using the property ID
  1662. *
  1663. * @param $basetable
  1664. * The base table for which the property should be deleted. Thus to deleted a property
  1665. * for a feature the basetable=feature and property is deleted from featureprop
  1666. * @param $record_id
  1667. * The primary key of the basetable to delete a property for. This should be in integer.
  1668. *
  1669. * @return
  1670. * Return True on Delete and False otherwise
  1671. *
  1672. * @ingroup tripal_chado_api
  1673. */
  1674. function tripal_core_delete_property_by_id($basetable, $record_id) {
  1675. // get the foreign key for this property table
  1676. $table_desc = module_invoke_all('chado_' . $basetable . 'prop_schema');
  1677. $pkcol = $table_desc['primary key'][0];
  1678. // construct the array that will match the exact record to update
  1679. $match = array(
  1680. $pkcol => $record_id,
  1681. );
  1682. return tripal_core_chado_delete($basetable . 'prop', $match);
  1683. }
  1684. /**
  1685. * This function is typically used in the '.install' file for a Tripal module
  1686. * Each module should call this function during installation to create
  1687. * the module data directory which is sites/default/files/tripal/[module_name]
  1688. * for default Drupal settings. This directory can then be used by the module
  1689. * for storing files.
  1690. *
  1691. * @param $module_name
  1692. * the name of the module being installed.
  1693. *
  1694. * @returns
  1695. * nothing
  1696. *
  1697. * @ingroup tripal_files_api
  1698. */
  1699. function tripal_create_moddir($module_name) {
  1700. // make the data directory for this module
  1701. $data_dir = file_directory_path() . "/tripal/$module_name";
  1702. if (!file_check_directory($data_dir, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
  1703. $message = "Cannot create directory $data_dir. This module may not ".
  1704. "behave correctly without this directory. Please create ".
  1705. "the directory manually or fix the problem and reinstall.";
  1706. drupal_set_message(check_plain(t($message)), 'error');
  1707. watchdog('tripal_core', $message, array(), WATCHDOG_ERROR);
  1708. }
  1709. }
  1710. /**
  1711. * Each Tripal module has a unique data directory which was creatd using the
  1712. * tripal_create_moddir function during installation. This function
  1713. * retrieves the directory path.
  1714. *
  1715. * @param $module_name
  1716. * The name of the module
  1717. *
  1718. * @returns
  1719. * The path within the Drupal installation where the data directory resides
  1720. * @ingroup tripal_files_api
  1721. */
  1722. function tripal_get_moddir($module_name) {
  1723. $data_dir = file_directory_path() . "/tripal/$module_name";
  1724. return $data_dir;
  1725. }
  1726. /**
  1727. * Set the Tripal Database
  1728. *
  1729. * The tripal_db_set_active function is used to prevent namespace collisions
  1730. * when chado and drupal are installed in the same database but in different
  1731. * schemas. It is also used for backwards compatibility with older versions
  1732. * of tripal or in cases where chado is located outside of the Drupal database.
  1733. *
  1734. * @ingroup tripal_chado_api
  1735. */
  1736. function tripal_db_set_active($dbname) {
  1737. global $db_url, $db_type;
  1738. $chado_exists = 0;
  1739. // only postgres can support search paths. So if this is MysQL then
  1740. // just run the normal tripal_db_set_active function.
  1741. if (strcmp($db_type, 'pgsql')==0) {
  1742. // if the 'chado' database is in the $db_url variable then chado is
  1743. // not in the same Drupal database
  1744. if (is_array($db_url)) {
  1745. if (isset($db_url[$dbname])) {
  1746. return db_set_active($dbname);
  1747. }
  1748. }
  1749. // check to make sure the chado schema exists
  1750. $chado_exists = tripal_core_chado_schema_exists();
  1751. // here we make the assumption that the default database schema is
  1752. // 'public'. This will most likely always be the case but if not,
  1753. // then this code will break
  1754. if ($chado_exists && strcmp($dbname, 'chado')==0) {
  1755. db_query("set search_path to %s", 'chado,public');
  1756. return 'public,chado';
  1757. }
  1758. elseif ($chado_exists) {
  1759. db_query("set search_path to %s", 'public,chado');
  1760. return 'chado,public';
  1761. }
  1762. else {
  1763. return db_set_active($dbname);
  1764. }
  1765. }
  1766. else {
  1767. return db_set_active($dbname);
  1768. }
  1769. }
  1770. /**
  1771. * Instantiate or Return a persistent chado connection
  1772. *
  1773. * NOTE: cannot use $active_db since a new connection is created each time
  1774. * db_set_active() is called
  1775. *
  1776. * @return
  1777. * A postgresql connection object which can be used by pg_prepare, pg_execute, etc.
  1778. */
  1779. function tripal_db_persistent_chado() {
  1780. global $db_url;
  1781. // get connection if it already exists
  1782. $connection = variable_get('tripal_perisistent_chado',NULL);
  1783. if ($connection) {
  1784. return $connection;
  1785. // Otherwise we need to set it
  1786. } else {
  1787. if (is_array($db_url) && isset($db_url['chado'])) {
  1788. $connection = db_connect($db_url['chado']);
  1789. variable_set('tripal_perisistent_chado', $connection);
  1790. } else {
  1791. $connection = db_connect($db_url);
  1792. variable_set('tripal_perisistent_chado', $connection);
  1793. }
  1794. return $connection;
  1795. }
  1796. return FALSE;
  1797. }
  1798. /**
  1799. * Release a persistent chado connection
  1800. */
  1801. function tripal_db_release_persistent_chado () {
  1802. variable_del('tripal_perisistent_chado');
  1803. }
  1804. /**
  1805. * Purpose: Get max rank for a given set of criteria
  1806. * This function was developed with the many property tables in chado in mind
  1807. *
  1808. * @param $tablename
  1809. * The name of the chado table you want to select the max rank from this table must contain a
  1810. * rank column of type integer
  1811. * @param $where_options
  1812. * where options should include the id and type for that table to correctly
  1813. * group a set of records together where the only difference are the value and rank
  1814. * @code
  1815. * array(
  1816. * <column_name> => array(
  1817. * 'type' => <type of column: INT/STRING>,
  1818. * 'value' => <the value you want to filter on>,
  1819. * 'exact' => <if TRUE use =; if FALSE use ~>,
  1820. * )
  1821. * )
  1822. * @endcode
  1823. * @return the maximum rank
  1824. *
  1825. * @ingroup tripal_chado_api
  1826. */
  1827. function tripal_get_max_chado_rank($tablename, $where_options) {
  1828. $where= array();
  1829. //generate the where clause from supplied options
  1830. // the key is the column name
  1831. foreach ($where_options as $key => $val_array) {
  1832. if (preg_match('/INT/', $val_array['type'])) {
  1833. $where[] = $key . "=" . $val_array['value'];
  1834. }
  1835. else {
  1836. if ($val_array['exact']) {
  1837. $operator='=';
  1838. }
  1839. else {
  1840. $operator='~';
  1841. }
  1842. $where[] = $key . $operator . "'" . $val_array['value'] . "'";
  1843. }
  1844. }
  1845. $previous_db = tripal_db_set_active('chado');
  1846. $result = db_fetch_object(db_query(
  1847. "SELECT max(rank) as max_rank, count(rank) as count FROM %s WHERE %s",
  1848. $tablename,
  1849. implode(' AND ', $where)
  1850. ));
  1851. tripal_db_set_active($previous_db);
  1852. //drupal_set_message("Max Rank Query=SELECT max(rank) as max_rank, count(rank) as count FROM ".$tablename." WHERE ".implode(' AND ',$where));
  1853. if ($result->count > 0) {
  1854. return $result->max_rank;
  1855. }
  1856. else {
  1857. return -1;
  1858. }
  1859. }
  1860. /**
  1861. * Add a new table to the Chado schema. This function is simply a wrapper for
  1862. * the db_create_table() function of Drupal, but ensures the table is created
  1863. * inside the Chado schema rather than the Drupal schema. If the table already
  1864. * exists then it will be dropped and recreated using the schema provided.
  1865. * Howver, it will only drop a table if it exsits in the tripal_custom_tables
  1866. * table. This way the function cannot be used to accidentally alter existing
  1867. * non custom tables.
  1868. *
  1869. * @param $ret
  1870. * Array to which query results will be added.
  1871. * @param $table
  1872. * The name of the table to create.
  1873. * @param $schema
  1874. * A Drupal-style Schema API definition of the table
  1875. *
  1876. * @return
  1877. * A database query result resource for the new table, or FALSE if table was not constructed.
  1878. *
  1879. * @ingroup tripal_core_api
  1880. */
  1881. function tripal_create_chado_table(&$ret, $table, $schema) {
  1882. $ret = array();
  1883. // If the table exits in Chado but not in the tripal_custom_tables field
  1884. // then call an error. if the table exits in the tripal_custom_tables but
  1885. // not in Chado then create the table and replace the entry.
  1886. $sql = "SELECT * FROM {tripal_custom_tables} WHERE table_name = '%s'";
  1887. $centry = db_fetch_object(db_query($sql, $table));
  1888. $previous_db = tripal_db_set_active('chado'); // use chado database
  1889. $exists = db_table_exists($table);
  1890. tripal_db_set_active($previous_db); // now use drupal database
  1891. if (!$exists) {
  1892. $previous_db = tripal_db_set_active('chado'); // use chado database
  1893. db_create_table($ret, $table, $schema);
  1894. tripal_db_set_active($previous_db); // now use drupal database
  1895. if (count($ret)==0) {
  1896. watchdog('tripal_core', "Error adding custom table '!table_name'.",
  1897. array('!table_name' => $table), WATCHDOG_ERROR);
  1898. return FALSE;
  1899. }
  1900. }
  1901. if ($exists and !$centry) {
  1902. watchdog('tripal_core', "Could not add custom table '!table_name'. It ".
  1903. "already exists but is not known to Tripal as being a custom table.",
  1904. array('!table_name' => $table), WATCHDOG_WARNING);
  1905. return FALSE;
  1906. }
  1907. if ($exists and $centry) {
  1908. // drop the table we'll recreate it with the new schema
  1909. $previous_db = tripal_db_set_active('chado'); // use chado database
  1910. db_drop_table($ret, $table);
  1911. db_create_table($ret, $table, $schema);
  1912. tripal_db_set_active($previous_db); // now use drupal database
  1913. }
  1914. // if the table creation was succesful then add an entry
  1915. // in the tripal_custom_table
  1916. $record = new stdClass();
  1917. $record->table_name = $table;
  1918. $record->schema = serialize($schema);
  1919. // if an entry already exists then remove it
  1920. if ($centry) {
  1921. $sql = "DELETE FROM {tripal_custom_tables} WHERE table_name = '%s'";
  1922. db_query($sql, $table);
  1923. }
  1924. $success = drupal_write_record('tripal_custom_tables', $record);
  1925. if (!$success) {
  1926. watchdog('tripal_core', "Error adding custom table.",
  1927. array('!table_name' => $table), WATCHDOG_ERROR);
  1928. return FALSE;
  1929. }
  1930. return $ret;
  1931. }
  1932. /**
  1933. * Retrieves the schema in an array for the specified custom table.
  1934. *
  1935. * @param $table
  1936. * The name of the table to create.
  1937. *
  1938. * @return
  1939. * A Drupal-style Schema API array definition of the table. Returns
  1940. * FALSE on failure.
  1941. *
  1942. * @ingroup tripal_core_api
  1943. */
  1944. function tripal_get_chado_custom_schema($table) {
  1945. $sql = "SELECT schema FROM {tripal_custom_tables} WHERE table_name = '%s'";
  1946. $custom = db_fetch_object(db_query($sql, $table));
  1947. if (!$custom) {
  1948. return FALSE;
  1949. }
  1950. else {
  1951. return unserialize($custom->schema);
  1952. }
  1953. }
  1954. /**
  1955. * Check that the Chado schema exists
  1956. *
  1957. * @return
  1958. * TRUE/FALSE depending upon whether it exists
  1959. */
  1960. function tripal_core_chado_schema_exists() {
  1961. // This is postgresql-specific code to check the existence of the chado schema
  1962. $sql = "SELECT nspname FROM pg_catalog.pg_namespace WHERE nspname = 'chado'";
  1963. if (db_fetch_object(db_query($sql))) {
  1964. return TRUE;
  1965. }
  1966. else {
  1967. return FALSE;
  1968. }
  1969. }