tripal_core.api.inc 76 KB

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