tripal_core.api.inc 79 KB

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