tripal_core.api.inc 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747
  1. <?php
  2. require_once "tripal_core.schema_v1.2.api.inc";
  3. require_once "tripal_core.schema_v1.11.api.inc";
  4. /**
  5. * @file
  6. * The Tripal Core API
  7. *
  8. * This file provides the API needed for all other Tripal and Tripal dependent
  9. * modules.
  10. *
  11. * @defgroup tripal_api Tripal API
  12. * @{
  13. * Provides an application programming interface (API) for Tripal
  14. *
  15. * The Tripal API currently provides generic insert/update/select functions for all chado content as
  16. * well as some module specific functions that insert/update/delete/select specific chado content.
  17. *
  18. * This API is currently in its infancy and some necessary functions might be missing. If you find
  19. * a missing function that you think should be included go to the sourceforge feature request
  20. * page and request it's inclusion in the API. Such feature requests with a working function
  21. * definition will be given priority.
  22. * @}
  23. *
  24. * @defgroup tripal_chado_api Core Module Chado API
  25. * @{
  26. * Provides an application programming interface (API) to manage data withing the Chado database.
  27. * This includes functions for selecting, inserting, updating and deleting records
  28. * in Chado tables. The functions will ensure proper integrity contraints are met
  29. * for inserts and updates.
  30. *
  31. * Also, a set of functions is provided for creating template variables. First,
  32. * is the tripal_core_generate_chado_vars which is used to select one ore more
  33. * records from a table and return an array with foreign key relationships fully
  34. * populated. For example, if selecting a feature, the organism_id and type_id
  35. * would be present in the returned array as a nested array with their respective
  36. * foreign keys also nested. The only fields that are not included are text
  37. * fields (which may be very large) or many-to-many foreign key relationships.
  38. * However, these fields and relationships can be expanded using the
  39. * tripal_core_expand_chado_vars.
  40. *
  41. * When a row from a chado table is selected using these two functions, it provides
  42. * a way for users who want to cutomize Drupal template files to access all data
  43. * associate with a specific record.
  44. *
  45. * Finally, the property tables in Chado generally follow the same format. Therefore
  46. * there is a set of functions for inserting, updating and deleting properties for
  47. * any table. This provides quick lookup of properties (provided the CV term is
  48. * known).
  49. *
  50. * @}
  51. * @ingroup tripal_api
  52. *
  53. * @defgroup tripal_files_api Core Module Files API
  54. * @{
  55. * Provides an application programming interface (API) for managing files within
  56. * the Tripal data directory structure.
  57. *
  58. * @}
  59. * @ingroup tripal_api
  60. /**
  61. * Provides a generic routine for inserting into any Chado table
  62. *
  63. * Use this function to insert a record into any Chado table. The first
  64. * argument specifies the table for inserting and the second is an array
  65. * of values to be inserted. The array is mutli-dimensional such that
  66. * foreign key lookup values can be specified.
  67. *
  68. * @param $table
  69. * The name of the chado table for inserting
  70. * @param $values
  71. * An associative array containing the values for inserting.
  72. * @param $options
  73. * An array of options such as:
  74. * - statement_name: the name of the prepared statement to use. If the statement
  75. * has not yet been prepared it will be prepared automatically. On subsequent
  76. * calls with the same statement_name only an execute on the previously
  77. * prepared statement will occur.
  78. * - is_prepared: TRUE or FALSE. Whether or not the statement is prepared. By
  79. * default if the statement is not prepared it will be automatically.
  80. * However to avoid this check, which requires a database query you can
  81. * set this value to true and the check will not be performed.
  82. * - skip_validation: TRUE or FALSE. If TRUE will skip all the validation steps and
  83. * just try to insert as is. This is much faster but results in unhandled
  84. * non user-friendly errors if the insert fails.
  85. *
  86. * @return
  87. * On success this function returns TRUE. On failure, it returns FALSE.
  88. *
  89. * Example usage:
  90. * @code
  91. * $values = array(
  92. * 'organism_id' => array(
  93. * 'genus' => 'Citrus',
  94. * 'species' => 'sinensis',
  95. * ),
  96. * 'name' => 'orange1.1g000034m.g',
  97. * 'uniquename' => 'orange1.1g000034m.g',
  98. * 'type_id' => array (
  99. * 'cv_id' => array (
  100. * 'name' => 'sequence',
  101. * ),
  102. * 'name' => 'gene',
  103. * 'is_obsolete' => 0
  104. * ),
  105. * );
  106. * $result = tripal_core_chado_insert('feature',$values);
  107. * @endcode
  108. * The above code inserts a record into the feature table. The $values array is
  109. * nested such that the organism is selected by way of the organism_id foreign
  110. * key constraint by specifying the genus and species. The cvterm is also
  111. * specified using its foreign key and the cv_id for the cvterm is nested as
  112. * well.
  113. *
  114. * @ingroup tripal_chado_api
  115. */
  116. function tripal_core_chado_insert($table, $values, $options = array()) {
  117. // set defaults for options. If we don't set defaults then
  118. // we get memory leaks when we try to access the elements
  119. if (!is_array($options)) {
  120. $options = array();
  121. }
  122. if (!array_key_exists('is_prepared', $options)) {
  123. $options['is_prepared'] = FALSE;
  124. }
  125. if (!array_key_exists('statement_name',$options)) {
  126. $options['statement_name'] = FALSE;
  127. }
  128. if (!array_key_exists('skip_validation',$options)) {
  129. $options['skip_validation'] = FALSE;
  130. }
  131. $insert_values = array();
  132. // Determine plan of action
  133. if ($options['statement_name']) {
  134. // we have a prepared statment (or want to create one) so set $prepared = TRUE
  135. $prepared = TRUE;
  136. // we need to get a persistent connection. If one exists this function
  137. // will not recreate it, but if not it will create one and store it in
  138. // a Drupal variable for reuse later.
  139. $connection = tripal_db_persistent_chado();
  140. }
  141. else {
  142. //print "NO STATEMENT (insert): $table\n";
  143. //debug_print_backtrace();
  144. }
  145. if (array_key_exists('skip_validation', $options)) {
  146. $validate = !$options['skip_validation'];
  147. }
  148. else {
  149. $validate = TRUE;
  150. }
  151. // get the table description
  152. $table_desc = tripal_core_get_chado_table_schema($table);
  153. if (empty($table_desc)) {
  154. watchdog('tripal_core', 'tripal_core_chado_insert: There is no table description for !table_name', array('!table_name' => $table), WATCHDOG_WARNING);
  155. }
  156. // iterate through the values array and create a new 'insert_values' array
  157. // that has all the values needed for insert with all foreign relationsihps
  158. // resolved.
  159. foreach ($values as $field => $value) {
  160. if (is_array($value)) {
  161. $foreign_options = array();
  162. if ($options['statement_name']) {
  163. // add the fk relationship info to the prepared statement name so that
  164. // we can prepare the selects run by the recrusive tripal_core_chado_get_foreign_key
  165. // function.
  166. $foreign_options['statement_name'] = "fk_" . $table . "_" . $field;
  167. }
  168. // select the value from the foreign key relationship for this value
  169. $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value, $foreign_options);
  170. if (sizeof($results) > 1) {
  171. 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);
  172. }
  173. elseif (sizeof($results) < 1) {
  174. //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);
  175. }
  176. else {
  177. $insert_values[$field] = $results[0];
  178. }
  179. }
  180. else {
  181. $insert_values[$field] = $value;
  182. }
  183. }
  184. if ($validate) {
  185. // check for violation of any unique constraints
  186. $ukeys = $table_desc['unique keys'];
  187. $ukselect_cols = array();
  188. $ukselect_vals = array();
  189. if ($ukeys) {
  190. foreach ($ukeys as $name => $fields) {
  191. foreach ($fields as $index => $field) {
  192. // build the arrays for performing a select that will check the contraint
  193. $ukselect_cols[] = $field;
  194. $ukselect_vals[$field] = $insert_values[$field];
  195. }
  196. // now check the constraint
  197. $coptions = array('statement_name' => 'uqsel_' . $table . '_' . $name);
  198. if (tripal_core_chado_select($table, $ukselect_cols, $ukselect_vals, $coptions)) {
  199. watchdog('tripal_core', "tripal_core_chado_insert: Cannot insert duplicate record into $table table: " . print_r($values, 1), array(), 'WATCHDOG_ERROR');
  200. return FALSE;
  201. }
  202. }
  203. }
  204. // if trying to insert a field that is the primary key, make sure it also is unique
  205. $pkey = $table_desc['primary key'][0];
  206. if ($insert_values[$pkey]) {
  207. $coptions = array('statement_name' => 'pqsel_' . $table . '_' . $pkey);
  208. if (tripal_core_chado_select($table, array($pkey), array($pkey => $insert_values[$pkey]), $coptions)) {
  209. watchdog('tripal_core', "tripal_core_chado_insert: Cannot insert duplicate primary key into $table table: " . print_r($values, 1), array(), 'WATCHDOG_ERROR');
  210. return FALSE;
  211. }
  212. }
  213. // make sure required fields have a value
  214. if (!is_array($table_desc['fields'])) {
  215. $table_desc['fields'] = array();
  216. watchdog('tripal_core', "tripal_core_chado_insert: %table not defined in tripal schema api", array('%table' => $table), 'WATCHDOG WARNING');
  217. }
  218. foreach ($table_desc['fields'] as $field => $def) {
  219. // a field is considered missing if it cannot be NULL and there is no default
  220. // value for it or it is of type 'serial'
  221. if ($def['not NULL'] == 1 and !array_key_exists($field, $insert_values) and !isset($def['default']) and strcmp($def['type'], serial) != 0) {
  222. watchdog('tripal_core', "tripal_core_chado_insert: Field $table.$field cannot be NULL: " . print_r($values, 1), array(), 'WATCHDOG_ERROR');
  223. return FALSE;
  224. }
  225. }
  226. } //end of validation
  227. // Now build the insert SQL statement
  228. $ifields = array(); // contains the names of the fields
  229. $ivalues = array(); // contains the values of the fields
  230. $itypes = array(); // contains %d/%s placeholders for the sql query
  231. $iplaceholders = array(); // contains $1/$2 placeholders for the prepare query
  232. $idatatypes = array(); // contains the data type of the fields (int, text, etc.)
  233. $i = 1;
  234. foreach ($insert_values as $field => $value) {
  235. $ifields[] = $field;
  236. $ivalues[] = $value;
  237. $iplaceholders[] = '$' . $i;
  238. $i++;
  239. if (strcmp($value, '__NULL__')==0) {
  240. $itypes[] = "NULL";
  241. $idatatypes[] = "NULL";
  242. }
  243. elseif (strcasecmp($table_desc['fields'][$field]['type'], 'serial')==0 OR
  244. strcasecmp($table_desc['fields'][$field]['type'], 'int')==0 OR
  245. strcasecmp($table_desc['fields'][$field]['type'], 'integer')==0) {
  246. $itypes[] = "%d";
  247. $idatatypes[] = 'int';
  248. }
  249. elseif (strcasecmp($table_desc['fields'][$field]['type'], 'boolean')==0) {
  250. $itypes[] = "%s";
  251. $idatatypes[] = 'bool';
  252. }
  253. elseif (strcasecmp($table_desc['fields'][$field]['type'], 'float')==0) {
  254. $itypes[] = "%s";
  255. $idatatypes[] = 'numeric';
  256. }
  257. else {
  258. $itypes[] = "'%s'";
  259. $idatatypes[] = 'text';
  260. }
  261. }
  262. // create the SQL
  263. $sql = "INSERT INTO {$table} (" . implode(", ", $ifields) . ") VALUES (" . implode(", ", $itypes) . ")";
  264. // if this is a prepared statement then execute it
  265. if ($prepared) {
  266. // if this is the first time we've run this query
  267. // then we need to do the prepare, otherwise just execute
  268. if ($options['is_prepared'] != TRUE and
  269. !tripal_core_is_sql_prepared($options['statement_name'])) {
  270. // prepare the statement
  271. $psql = "PREPARE " . $options['statement_name'] . " (" . implode(', ', $idatatypes) . ") AS INSERT INTO {$table} (" . implode(", ", $ifields) . ") VALUES (" . implode(", ", $iplaceholders) . ")";
  272. $status = chado_query($psql);
  273. if (!$status) {
  274. watchdog('tripal_core', "tripal_core_chado_insert: not able to prepare '%name' statement for: %sql", array('%name' => $options['statement_name'], '%sql' => $sql), 'WATCHDOG ERROR');
  275. return FALSE;
  276. }
  277. }
  278. $sql = "EXECUTE " . $options['statement_name'] . "(" . implode(", ", $itypes) . ")";
  279. $result = chado_query($sql, $ivalues);
  280. }
  281. // if it's not a prepared statement then insert normally
  282. else {
  283. $previous_db = tripal_db_set_active('chado'); // use chado database
  284. $result = db_query($sql, $ivalues);
  285. tripal_db_set_active($previous_db); // now use drupal database
  286. }
  287. // if we have a result then add primary keys to return array
  288. if ($result) {
  289. $primary_key = array();
  290. if (!is_array($table_desc['primary key'])) {
  291. $table_desc['primary key'] = array();
  292. watchdog('tripal_core', "tripal_core_chado_insert: %table not defined in tripal schema api", array('%table' => $table), 'WATCHDOG WARNING');
  293. }
  294. foreach ($table_desc['primary key'] as $field) {
  295. $value = db_last_insert_id($table, $field);
  296. $values[$field] = $value;
  297. }
  298. return $values;
  299. }
  300. else {
  301. watchdog('tripal_core', "tripal_core_chado_insert: Cannot insert record into $table table: " . print_r($values, 1), array(), 'WATCHDOG_ERROR');
  302. return FALSE;
  303. }
  304. return FALSE;
  305. }
  306. /**
  307. * Provides a generic routine for updating into any Chado table
  308. *
  309. * Use this function to update a record in any Chado table. The first
  310. * argument specifies the table for inserting, the second is an array
  311. * of values to matched for locating the record for updating, and the third
  312. * argument give the values to update. The arrays are mutli-dimensional such
  313. * that foreign key lookup values can be specified.
  314. *
  315. * @param $table
  316. * The name of the chado table for inserting
  317. * @param $match
  318. * An associative array containing the values for locating a record to update.
  319. * @param $values
  320. * An associative array containing the values for updating.
  321. * @param $options
  322. * An array of options such as:
  323. * - statement_name: the name of the prepared statement to use. If the statement
  324. * has not yet been prepared it will be prepared automatically. On subsequent
  325. * calls with the same statement_name only an execute on the previously
  326. * prepared statement will occur.
  327. * - is_prepared: TRUE or FALSE. Whether or not the statement is prepared. By
  328. * default if the statement is not prepared it will be automatically.
  329. * However to avoid this check, which requires a database query you can
  330. * set this value to true and the check will not be performed.
  331. * @return
  332. * On success this function returns TRUE. On failure, it returns FALSE.
  333. *
  334. * Example usage:
  335. * @code
  336. $umatch = array(
  337. 'organism_id' => array(
  338. 'genus' => 'Citrus',
  339. 'species' => 'sinensis',
  340. ),
  341. 'uniquename' => 'orange1.1g000034m.g7',
  342. 'type_id' => array (
  343. 'cv_id' => array (
  344. 'name' => 'sequence',
  345. ),
  346. 'name' => 'gene',
  347. 'is_obsolete' => 0
  348. ),
  349. );
  350. $uvalues = array(
  351. 'name' => 'orange1.1g000034m.g',
  352. 'type_id' => array (
  353. 'cv_id' => array (
  354. 'name' => 'sequence',
  355. ),
  356. 'name' => 'mRNA',
  357. 'is_obsolete' => 0
  358. ),
  359. );
  360. * $result = tripal_core_chado_update('feature',$umatch,$uvalues);
  361. * @endcode
  362. * The above code species that a feature with a given uniquename, organism_id,
  363. * and type_id (the unique constraint for the feature table) will be updated.
  364. * The organism_id is specified as a nested array that uses the organism_id
  365. * foreign key constraint to lookup the specified values to find the exact
  366. * organism_id. The same nested struture is also used for specifying the
  367. * values to update. The function will find the record that matches the
  368. * columns specified and update the record with the avlues in the $uvalues array.
  369. *
  370. * @ingroup tripal_chado_api
  371. */
  372. function tripal_core_chado_update($table, $match, $values, $options = NULL) {
  373. // set defaults for options. If we don't set defaults then
  374. // we get memory leaks when we try to access the elements
  375. if (!is_array($options)) {
  376. $options = array();
  377. }
  378. if (!array_key_exists('is_prepared', $options)) {
  379. $options['is_prepared'] = FALSE;
  380. }
  381. if (!array_key_exists('statement_name',$options)) {
  382. $options['statement_name'] = FALSE;
  383. }
  384. $update_values = array(); // contains the values to be updated
  385. $update_matches = array(); // contains the values for the where clause
  386. // Determine plan of action
  387. if ($options['statement_name']) {
  388. // we have a prepared statment (or want to create one) so set $prepared = TRUE
  389. $prepared = TRUE;
  390. // we need to get a persistent connection. If one exists this function
  391. // will not recreate it, but if not it will create one and store it in
  392. // a Drupal variable for reuse later.
  393. $connection = tripal_db_persistent_chado();
  394. }
  395. else {
  396. //print "NO STATEMENT (update): $table\n";
  397. //debug_print_backtrace();
  398. }
  399. // get the table description
  400. $table_desc = tripal_core_get_chado_table_schema($table);
  401. // get the values needed for matching in the SQL statement
  402. foreach ($match as $field => $value) {
  403. if (is_array($value)) {
  404. $foreign_options = array();
  405. if ($options['statement_name']) {
  406. // add the fk relationship info to the prepared statement name so that
  407. // we can prepare the selects run by the recrusive tripal_core_chado_get_foreign_key
  408. // function.
  409. $foreign_options['statement_name'] = "fk_" . $table . "_" . $field;
  410. }
  411. $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value, $foreign_options);
  412. if (sizeof($results) > 1) {
  413. 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);
  414. }
  415. elseif (sizeof($results) < 1) {
  416. //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);
  417. }
  418. else {
  419. $update_matches[$field] = $results[0];
  420. }
  421. }
  422. else {
  423. $update_matches[$field] = $value;
  424. }
  425. }
  426. // get the values used for updating
  427. foreach ($values as $field => $value) {
  428. if (is_array($value)) {
  429. $foreign_options = array();
  430. // select the value from the foreign key relationship for this value
  431. if ($options['statement_name']) {
  432. // add the fk relationship info to the prepared statement name so that
  433. // we can prepare the selects run by the recrusive tripal_core_chado_get_foreign_key
  434. // function.
  435. $foreign_options['statement_name'] = "fk_" . $table . "_" . $field;
  436. }
  437. $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value, $foreign_options);
  438. if (sizeof($results) > 1) {
  439. 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);
  440. }
  441. elseif (sizeof($results) < 1) {
  442. //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);
  443. }
  444. else {
  445. $update_values[$field] = $results[0];
  446. }
  447. }
  448. else {
  449. $update_values[$field] = $value;
  450. }
  451. }
  452. // now build the SQL statement
  453. $sql = "UPDATE {$table} SET ";
  454. $psql = "UPDATE {$table} SET ";
  455. $uargs = array();
  456. $idatatypes = array();
  457. $pvalues = array();
  458. $ivalues = array();
  459. $i = 1;
  460. foreach ($update_values as $field => $value) {
  461. if (strcasecmp($table_desc['fields'][$field]['type'], 'serial')==0 OR
  462. strcasecmp($table_desc['fields'][$field]['type'], 'int')==0 OR
  463. strcasecmp($table_desc['fields'][$field]['type'], 'integer')==0) {
  464. if (strcmp($value, '__NULL__') == 0) {
  465. $sql .= " $field = %s, ";
  466. $ivalues[] = 'NULL';
  467. $pvalues[] = '%s';
  468. $uargs[] = 'NULL';
  469. }
  470. else {
  471. $sql .= " $field = %d, ";
  472. $ivalues[] = $value;
  473. $pvalues[] = '%d';
  474. $uargs[] = $value;
  475. }
  476. $idatatypes[] = 'int';
  477. }
  478. elseif (strcasecmp($table_desc['fields'][$field]['type'], 'boolean')==0) {
  479. $sql .= " $field = %s, ";
  480. $pvalues[] = '%s';
  481. if (strcmp($value, '__NULL__')==0) {
  482. $ivalues[] = 'NULL';
  483. $uargs[] = 'NULL';
  484. }
  485. else {
  486. $ivalues[] = $value;
  487. $uargs[] = $value;
  488. }
  489. $idatatypes[] = 'bool';
  490. }
  491. elseif (strcasecmp($table_desc['fields'][$field]['type'], 'float')==0) {
  492. $sql .= " $field = %s, ";
  493. $pvalues[] = '%s';
  494. if (strcmp($value, '__NULL__')==0) {
  495. $ivalues[] = 'NULL';
  496. $uargs[] = 'NULL';
  497. }
  498. else {
  499. $ivalues[] = $value;
  500. $uargs[] = $value;
  501. }
  502. $idatatypes[] = 'numeric';
  503. }
  504. else {
  505. if (strcmp($value, '__NULL__') == 0) {
  506. $sql .= " $field = %s, ";
  507. $ivalues[] = 'NULL';
  508. $uargs[] = 'NULL';
  509. $pvalues[] = '%s';
  510. }
  511. else {
  512. $sql .= " $field = '%s', ";
  513. $ivalues[] = $value;
  514. $uargs[] = $value;
  515. $pvalues[] = "'%s'";
  516. }
  517. $idatatypes[] = 'text';
  518. }
  519. $psql .= "$field = \$" . $i . ", ";
  520. $i++;
  521. }
  522. $sql = drupal_substr($sql, 0, -2); // get rid of the trailing comma & space
  523. $psql = drupal_substr($psql, 0, -2); // get rid of the trailing comma & space
  524. $sql .= " WHERE ";
  525. $psql .= " WHERE ";
  526. foreach ($update_matches as $field => $value) {
  527. if (strcasecmp($table_desc['fields'][$field]['type'], 'serial')==0 OR
  528. strcasecmp($table_desc['fields'][$field]['type'], 'int')==0 OR
  529. strcasecmp($table_desc['fields'][$field]['type'], 'integer')==0) {
  530. if (strcmp($value, '__NULL__')==0) {
  531. $sql .= " $field = %s AND ";
  532. $ivalues[] = 'NULL';
  533. $uargs[] = 'NULL';
  534. $pvalues[] = '%s';
  535. }
  536. else {
  537. $sql .= " $field = %d AND ";
  538. $ivalues[] = $value;
  539. $uargs[] = $value;
  540. $pvalues[] = '%s';
  541. }
  542. $idatatypes[] = 'int';
  543. }
  544. elseif (strcasecmp($table_desc['fields'][$field]['type'], 'boolean')==0) {
  545. $sql .= " $field = %s AND ";
  546. $pvalues[] = '%s';
  547. if (strcmp($value, '__NULL__')==0) {
  548. $ivalues[] = 'NULL';
  549. $uargs[] = 'NULL';
  550. }
  551. else {
  552. $ivalues[] = $value;
  553. $uargs[] = $value;
  554. }
  555. $idatatypes[] = 'bool';
  556. }
  557. elseif (strcasecmp($table_desc['fields'][$field]['type'], 'float')==0) {
  558. $sql .= " $field = %s AND ";
  559. $pvalues[] = '%s';
  560. if (strcmp($value, '__NULL__')==0) {
  561. $ivalues[] = 'NULL';
  562. $uargs[] = 'NULL';
  563. }
  564. else {
  565. $ivalues[] = $value;
  566. $uargs[] = $value;
  567. }
  568. $idatatypes[] = 'numeric';
  569. }
  570. else {
  571. if (strcmp($value, '__NULL__')==0) {
  572. $sql .= " $field = %s AND ";
  573. $ivalues[] = 'NULL';
  574. $uargs[] = 'NULL';
  575. $pvalues[] = '%s';
  576. }
  577. else {
  578. $sql .= " $field = '%s' AND ";
  579. $ivalues[] = $value;
  580. $uargs[] = $value;
  581. $pvalues[] = "'%s'";
  582. }
  583. $idatatypes[] = 'text';
  584. }
  585. $psql .= "$field = \$" . $i . " AND ";
  586. $i++;
  587. }
  588. $sql = drupal_substr($sql, 0, -4); // get rid of the trailing 'AND'
  589. $psql = drupal_substr($psql, 0, -4); // get rid of the trailing 'AND'
  590. // finish constructing the prepared SQL statement
  591. $psql = "PREPARE " . $options['statement_name'] . " (" . implode(', ', $idatatypes) . ") AS " . $psql;
  592. // finally perform the update. If successful, return the updated record
  593. if ($prepared) {
  594. // if this is the first time we've run this query
  595. // then we need to do the prepare, otherwise just execute
  596. if ($options['is_prepared'] != TRUE and
  597. !tripal_core_is_sql_prepared($options['statement_name'])) {
  598. $status = chado_query($psql);
  599. if (!$status) {
  600. watchdog('tripal_core', "tripal_core_chado_update: not able to prepare '%name' statement for: %sql", array('%name' => $options['statement_name'], '%sql' => $sql), 'WATCHDOG ERROR');
  601. return FALSE;
  602. }
  603. }
  604. $sql = "EXECUTE " . $options['statement_name'] . "(" . implode(", ", $pvalues) . ")";
  605. $resource = chado_query($sql, $ivalues);
  606. }
  607. // if it's not a prepared statement then insert normally
  608. else {
  609. $previous_db = tripal_db_set_active('chado'); // use chado database
  610. $resource = db_query($sql, $uargs);
  611. tripal_db_set_active($previous_db); // now use drupal database
  612. }
  613. if ($resource) {
  614. return TRUE;
  615. }
  616. else {
  617. watchdog('tripal_core', "Cannot update record in $table table. Match:" . print_r($match, 1) . ". Values: ". print_r($values, 1), array(), 'WATCHDOG_ERROR');
  618. return FALSE;
  619. }
  620. return FALSE;
  621. }
  622. /**
  623. * Provides a generic function for deleting a record(s) from any chado table
  624. *
  625. * Use this function to delete a record(s) in any Chado table. The first
  626. * argument specifies the table to delete from and the second is an array
  627. * of values to match for locating the record(s) to be deleted. The arrays
  628. * are mutli-dimensional such that foreign key lookup values can be specified.
  629. *
  630. * @param $table
  631. * The name of the chado table for inserting
  632. * @param $match
  633. * An associative array containing the values for locating a record to update.
  634. *
  635. * @return
  636. * On success this function returns TRUE. On failure, it returns FALSE.
  637. *
  638. * Example usage:
  639. * @code
  640. $umatch = array(
  641. 'organism_id' => array(
  642. 'genus' => 'Citrus',
  643. 'species' => 'sinensis',
  644. ),
  645. 'uniquename' => 'orange1.1g000034m.g7',
  646. 'type_id' => array (
  647. 'cv_id' => array (
  648. 'name' => 'sequence',
  649. ),
  650. 'name' => 'gene',
  651. 'is_obsolete' => 0
  652. ),
  653. );
  654. $uvalues = array(
  655. 'name' => 'orange1.1g000034m.g',
  656. 'type_id' => array (
  657. 'cv_id' => array (
  658. 'name' => 'sequence',
  659. ),
  660. 'name' => 'mRNA',
  661. 'is_obsolete' => 0
  662. ),
  663. );
  664. * $result = tripal_core_chado_update('feature',$umatch,$uvalues);
  665. * @endcode
  666. * The above code species that a feature with a given uniquename, organism_id,
  667. * and type_id (the unique constraint for the feature table) will be deleted.
  668. * The organism_id is specified as a nested array that uses the organism_id
  669. * foreign key constraint to lookup the specified values to find the exact
  670. * organism_id. The same nested struture is also used for specifying the
  671. * values to update. The function will find all records that match the
  672. * columns specified and delete them.
  673. *
  674. * @ingroup tripal_chado_api
  675. */
  676. function tripal_core_chado_delete($table, $match) {
  677. $delete_matches = array(); // contains the values for the where clause
  678. // get the table description
  679. $table_desc = tripal_core_get_chado_table_schema($table);
  680. // get the values needed for matching in the SQL statement
  681. foreach ($match as $field => $value) {
  682. if (is_array($value)) {
  683. // if the user has specified an array of values to delete rather than
  684. // FK relationships the keep those in our match
  685. if (array_values($value) === $value) {
  686. $delete_matches[$field] = $value;
  687. }
  688. else {
  689. $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value);
  690. if (sizeof($results) > 1) {
  691. 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);
  692. }
  693. elseif (sizeof($results) < 1) {
  694. //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);
  695. }
  696. else {
  697. $delete_matches[$field] = $results[0];
  698. }
  699. }
  700. }
  701. else {
  702. $delete_matches[$field] = $value;
  703. }
  704. }
  705. // now build the SQL statement
  706. $sql = "DELETE FROM {$table} WHERE ";
  707. $dargs = array();
  708. foreach ($delete_matches as $field => $value) {
  709. if (count($value) > 1) {
  710. $sql .= "$field IN (" . db_placeholders($value, 'varchar') . ") AND ";
  711. foreach ($value as $v) {
  712. $dargs[] = $v;
  713. }
  714. }
  715. else {
  716. if (strcmp($value, '__NULL__') == 0) {
  717. $sql .= " $field = NULL AND ";
  718. }
  719. elseif (strcmp($fields[$field]['type'], 'serial') == 0 or
  720. strcmp($fields[$field]['type'], 'int') == 0) {
  721. $sql .= " $field = %d AND ";
  722. }
  723. else {
  724. $sql .= " $field = '%s' AND ";
  725. }
  726. array_push($dargs, $value);
  727. }
  728. }
  729. $sql = drupal_substr($sql, 0, -4); // get rid of the trailing 'AND'
  730. // finally perform the delete. If successful, return the updated record
  731. $previous_db = tripal_db_set_active('chado'); // use chado database
  732. $result = db_query($sql, $dargs);
  733. tripal_db_set_active($previous_db); // now use drupal database
  734. if ($result) {
  735. return TRUE;
  736. }
  737. else {
  738. watchdog('tripal_core', "Cannot delete record in $table table. Match:" . print_r($match, 1) . ". Values: ". print_r($values, 1), array(), 'WATCHDOG_ERROR');
  739. return FALSE;
  740. }
  741. return FALSE;
  742. }
  743. /**
  744. * Provides a generic routine for selecting data from a Chado table
  745. *
  746. * Use this function to perform a simple select from any Chado table.
  747. *
  748. * @param $table
  749. * The name of the chado table for inserting
  750. * @param $columns
  751. * An array of column names
  752. * @param $values
  753. * An associative array containing the values for filtering the results. In the
  754. * case where multiple values for the same time are to be selected an additional
  755. * entry for the field should appear for each value
  756. * @param $options
  757. * An associative array of additional options where the key is the option
  758. * and the value is the value of that option.
  759. *
  760. * Additional Options Include:
  761. * - has_record
  762. * Set this argument to 'TRUE' to have this function return a numeric
  763. * value for the number of recrods rather than the array of records. this
  764. * can be useful in 'if' statements to check the presence of particula records.
  765. * - return_sql
  766. * Set this to 'TRUE' to have this function return an array where the first
  767. * element is the sql that would have been run and the second is an array of
  768. * arguments.
  769. * - case_insensitive_columns
  770. * An array of columns to do a case insensitive search on.
  771. * - regex_columns
  772. * An array of columns where the value passed in should be treated as a regular expression
  773. * - order_by
  774. * An associative array containing the column names of the table as keys
  775. * and the type of sort (i.e. ASC, DESC) as the values. The results in the
  776. * query will be sorted by the key values in the direction listed by the value
  777. * - statement_name: the name of the prepared statement to use. If the statement
  778. * has not yet been prepared it will be prepared automatically. On subsequent
  779. * calls with the same statement_name only an execute on the previously
  780. * prepared statement will occur.
  781. * - is_prepared: TRUE or FALSE. Whether or not the statement is prepared. By
  782. * default if the statement is not prepared it will be automatically.
  783. * However to avoid this check, which requires a database query you can
  784. * set this value to true and the check will not be performed.
  785. *
  786. * @return
  787. * A database query result resource, FALSE if the query was not executed
  788. * correctly, or the number of records in the dataset if $has_record is set.
  789. *
  790. * Example usage:
  791. * @code
  792. * $columns = array('feature_id', 'name');
  793. * $values = array(
  794. * 'organism_id' => array(
  795. * 'genus' => 'Citrus',
  796. * 'species' => array('sinensis', 'clementina'),
  797. * ),
  798. * 'uniquename' => 'orange1.1g000034m.g',
  799. * 'type_id' => array (
  800. * 'cv_id' => array (
  801. * 'name' => 'sequence',
  802. * ),
  803. * 'name' => 'gene',
  804. * 'is_obsolete' => 0
  805. * ),
  806. * );
  807. * $options = array(
  808. * 'statement_name' => 'sel_feature_genus_species_cvname'
  809. * 'order_by' => array(
  810. * 'name' => 'ASC'
  811. * ),
  812. * );
  813. * $result = tripal_core_chado_select('feature',$columns,$values,$options);
  814. * @endcode
  815. * The above code selects a record from the feature table using the three fields
  816. * that uniquely identify a feature. The $columns array simply lists the columns
  817. * to select. The $values array is nested such that the organism is identified by
  818. * way of the organism_id foreign key constraint by specifying the genus and
  819. * species. The cvterm is also specified using its foreign key and the cv_id
  820. * for the cvterm is nested as well. In the example above, two different species
  821. * are allowed to match
  822. *
  823. * @ingroup tripal_chado_api
  824. */
  825. function tripal_core_chado_select($table, $columns, $values, $options = NULL) {
  826. // set defaults for options. If we don't set defaults then
  827. // we get memory leaks when we try to access the elements
  828. if (!is_array($options)) {
  829. $options = array();
  830. }
  831. if (!array_key_exists('case_insensitive_columns', $options)) {
  832. $options['case_insensitive_columns'] = array();
  833. }
  834. if (!array_key_exists('regex_columns', $options)) {
  835. $options['regex_columns'] = array();
  836. }
  837. if (!array_key_exists('order_by', $options)) {
  838. $options['order_by'] = array();
  839. }
  840. if (!array_key_exists('is_prepared', $options)) {
  841. $options['is_prepared'] = FALSE;
  842. }
  843. if (!array_key_exists('return_sql', $options)) {
  844. $options['return_sql'] = FALSE;
  845. }
  846. if (!array_key_exists('has_record', $options)) {
  847. $options['has_record'] = FALSE;
  848. }
  849. if (!array_key_exists('statement_name',$options)) {
  850. $options['statement_name'] = FALSE;
  851. }
  852. // if this is a prepared statement check to see if it has already been prepared
  853. if ($options['statement_name']) {
  854. $prepared = TRUE;
  855. // we need to get a persistent connection. If one exists this function
  856. // will not recreate it, but if not it will create one and store it in
  857. // a Drupal variable for reuse later.
  858. $connection = tripal_db_persistent_chado();
  859. }
  860. else {
  861. //print "NO STATEMENT (select): $table\n";
  862. //debug_print_backtrace();
  863. }
  864. // check that our columns and values arguments are proper arrays
  865. if (!is_array($columns)) {
  866. watchdog('tripal_core', 'the $columns argument for tripal_core_chado_select must be an array.');
  867. return FALSE;
  868. }
  869. if (!is_array($values)) {
  870. watchdog('tripal_core', 'the $values argument for tripal_core_chado_select must be an array.');
  871. return FALSE;
  872. }
  873. // get the table description
  874. $table_desc = tripal_core_get_chado_table_schema($table);
  875. $select = '';
  876. $from = '';
  877. $where = '';
  878. $args = array();
  879. foreach ($values as $field => $value) {
  880. $select[] = $field;
  881. if (is_array($value)) {
  882. // if the user has specified multiple values for matching then this we
  883. // want to catch that and save them in our $where array, otherwise
  884. // we'll descend for a foreign key relationship
  885. if (array_values($value) === $value) {
  886. $where[$field] = $value;
  887. }
  888. else {
  889. // select the value from the foreign key relationship for this value
  890. $foreign_options = array(
  891. 'regex_columns' => $options['regex_columns'],
  892. 'case_insensitive_columns' => $options['case_insensitive_columns']
  893. );
  894. if ($options['statement_name']) {
  895. // add the fk relationship info to the prepared statement name so that
  896. // we can prepare the selects run by the recrusive tripal_core_chado_get_foreign_key
  897. // function.
  898. $foreign_options['statement_name'] = "fk_" . $table . "_" . $field;
  899. }
  900. $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value, $foreign_options);
  901. if (!$results or count($results) ==0) {
  902. // foreign key records are required
  903. // thus if none matched then return FALSE and alert the admin through watchdog
  904. //watchdog('tripal_core',
  905. // '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',
  906. // array('!table' => $table,
  907. // '!columns' => '<pre>' . print_r($columns, TRUE) . '</pre>',
  908. // '!values' => '<pre>' . print_r($values, TRUE) . '</pre>',
  909. // '!field' => $field,
  910. // ),
  911. // WATCHDOG_WARNING);
  912. return array();
  913. }
  914. else {
  915. $where[$field] = $results;
  916. }
  917. }
  918. }
  919. else {
  920. //need to catch a 0 and make int if integer field
  921. if ($table_desc['fields'][$field]['type'] == 'int') {
  922. $where[$field][] = (int) $value;
  923. }
  924. else {
  925. $where[$field][] = $value;
  926. }
  927. }
  928. }
  929. // now build the SQL and prepared SQL statements. We may not use
  930. // the prepared statement if it wasn't requested in the options of if the
  931. // argument in a where statement has multiple values.
  932. if (empty($where)) {
  933. // sometimes want to select everything
  934. $sql = "SELECT " . implode(', ', $columns) . " ";
  935. $sql .= "FROM {$table} ";
  936. // we don't prepare a statement if there is no where clause
  937. $prepared = FALSE;
  938. }
  939. else {
  940. $sql = "SELECT " . implode(', ', $columns) . " ";
  941. $sql .= "FROM {$table} ";
  942. $sql .= "WHERE ";
  943. $psql = $sql; // prepared SQL statement;
  944. $i = 1;
  945. $pvalues = array();
  946. foreach ($where as $field => $value) {
  947. // if we have multiple values returned then we need an 'IN' statement
  948. // in our where statement
  949. if (count($value) > 1) {
  950. $sql .= "$field IN (" . db_placeholders($value, 'varchar') . ") AND ";
  951. foreach ($value as $v) {
  952. $args[] = $v;
  953. // we can't do a prepared statement with an 'IN' statement in a
  954. // where clause because we can't guarantee we'll always have the
  955. // same number of elements.
  956. $prepared = FALSE;
  957. }
  958. }
  959. // if we have a single value then we need an = in our where statement
  960. else {
  961. $operator = '=';
  962. if (in_array($field, $options['regex_columns'])) {
  963. $operator = '~*';
  964. }
  965. // get the types for the prepared statement. First check if the type
  966. // is an integer
  967. if (strcasecmp($table_desc['fields'][$field]['type'], 'serial')==0 OR
  968. strcasecmp($table_desc['fields'][$field]['type'], 'int')==0 OR
  969. strcasecmp($table_desc['fields'][$field]['type'], 'integer')==0) {
  970. $sql .= "$field $operator %d AND ";
  971. $psql .= "$field $operator \$" . $i . " AND ";
  972. $args[] = $value[0];
  973. // set the variables needed for the prepared statement
  974. $idatatypes[] = 'int';
  975. $pvalues[] = $value[0];
  976. }
  977. elseif (strcasecmp($table_desc['fields'][$field]['type'], 'boolean')==0) {
  978. $sql .= "$field $operator %s AND ";
  979. $psql .= "$field $operator \$" . $i . " AND ";
  980. $args[] = $value[0];
  981. // set the variables needed for the prepared statement
  982. $idatatypes[] = 'bool';
  983. $pvalues[] = $value[0];
  984. }
  985. elseif (strcasecmp($table_desc['fields'][$field]['type'], 'float')==0) {
  986. $sql .= "$field $operator %s AND ";
  987. $psql .= "$field $operator \$" . $i . " AND ";
  988. $args[] = $value[0];
  989. // set the variables needed for the prepared statement
  990. $idatatypes[] = 'numeric';
  991. $pvalues[] = $value[0];
  992. }
  993. // else the type is a text
  994. else {
  995. if (in_array($field, $options['case_insensitive_columns'])) {
  996. $sql .= "lower($field) $operator lower('%s') AND ";
  997. $psql .= "lower($field) $operator lower('\$" . $i . "') AND ";
  998. $args[] = $value;
  999. }
  1000. else {
  1001. $sql .= "$field $operator '%s' AND ";
  1002. $psql .= "$field $operator \$" . $i . " AND ";
  1003. $args[] = $value[0];
  1004. }
  1005. // set the variables needed for the prepared statement
  1006. $idatatypes[] = 'text';
  1007. $pvalues[] = "'" . $value[0] . "'";
  1008. }
  1009. }
  1010. $i++;
  1011. }
  1012. $sql = drupal_substr($sql, 0, -4); // get rid of the trailing 'AND '
  1013. $psql = drupal_substr($psql, 0, -4); // get rid of the trailing 'AND '
  1014. // finally add any ordering of the results to the SQL statement
  1015. if (count($options['order_by']) > 0) {
  1016. $sql .= " ORDER BY ";
  1017. $psql .= " ORDER BY ";
  1018. foreach ($options['order_by'] as $field => $dir) {
  1019. $sql .= "$field $dir, ";
  1020. $psql .= "$field $dir, ";
  1021. }
  1022. $sql = drupal_substr($sql, 0, -2); // get rid of the trailing ', '
  1023. $psql = drupal_substr($psql, 0, -2); // get rid of the trailing ', '
  1024. }
  1025. // finish constructing the prepared SQL statement
  1026. $psql = "PREPARE " . $options['statement_name'] . " (" . implode(', ', $idatatypes) . ") AS " . $psql;
  1027. } // end if(empty($where)){ } else {
  1028. // if the caller has requested the SQL rather than the results...
  1029. // which happens in the case of wanting to use the Drupal pager, then do so
  1030. if ($options['return_sql'] == TRUE) {
  1031. return array('sql' => $sql, 'args' => $args);
  1032. }
  1033. // prepare the statement
  1034. if ($prepared) {
  1035. // if this is the first time we've run this query
  1036. // then we need to do the prepare, otherwise just execute
  1037. if ($options['is_prepared'] != TRUE and
  1038. !tripal_core_is_sql_prepared($options['statement_name'])) {
  1039. $status = chado_query($psql);
  1040. if (!$status) {
  1041. watchdog('tripal_core', "tripal_core_chado_select: not able to prepare '%name' statement for: %sql", array('%name' => $options['statement_name'], '%sql' => $sql), 'WATCHDOG ERROR');
  1042. return FALSE;
  1043. }
  1044. }
  1045. $sql = "EXECUTE " . $options['statement_name'] . "(" . implode(", ", $pvalues) . ")";
  1046. // WARNING: This call creates a memory leak: if you remove the $ivalues it doesn't
  1047. // do this. Got to find out what's causing this.
  1048. $resource = chado_query($sql, $ivalues);
  1049. }
  1050. else {
  1051. $previous_db = tripal_db_set_active('chado'); // use chado database
  1052. $resource = db_query($sql, $args);
  1053. tripal_db_set_active($previous_db); // now use drupal database
  1054. }
  1055. // format results into an array
  1056. $results = array();
  1057. while ($r = db_fetch_object($resource)) {
  1058. $results[] = $r;
  1059. }
  1060. if ($options['has_record']) {
  1061. return count($results);
  1062. }
  1063. return $results;
  1064. }
  1065. /**
  1066. * Gets the value of a foreign key relationship
  1067. *
  1068. * This function is used by tripal_core_chado_select, tripal_core_chado_insert,
  1069. * and tripal_core_chado_update to iterate through the associate array of
  1070. * values that gets passed to each of those routines. The values array
  1071. * is nested where foreign key contraints are used to specify a value that. See
  1072. * documentation for any of those functions for further information.
  1073. *
  1074. * @param $table_desc
  1075. * A table description for the table with the foreign key relationship to be identified generated by
  1076. * hook_chado_<table name>_schema()
  1077. * @param $field
  1078. * The field in the table that is the foreign key.
  1079. * @param $values
  1080. * An associative array containing the values
  1081. * @param $options
  1082. * An associative array of additional options where the key is the option
  1083. * and the value is the value of that option. These options are passed on to tripal_core_chado_select.
  1084. *
  1085. * Additional Options Include:
  1086. * - case_insensitive_columns
  1087. * An array of columns to do a case insensitive search on.
  1088. * - regex_columns
  1089. * An array of columns where the value passed in should be treated as a regular expression
  1090. *
  1091. * @return
  1092. * A string containg the results of the foreign key lookup, or FALSE if failed.
  1093. *
  1094. * Example usage:
  1095. * @code
  1096. *
  1097. * $values = array(
  1098. * 'genus' => 'Citrus',
  1099. * 'species' => 'sinensis',
  1100. * );
  1101. * $value = tripal_core_chado_get_foreign_key('feature', 'organism_id',$values);
  1102. *
  1103. * @endcode
  1104. * The above code selects a record from the feature table using the three fields
  1105. * that uniquely identify a feature. The $columns array simply lists the columns
  1106. * to select. The $values array is nested such that the organism is identified by
  1107. * way of the organism_id foreign key constraint by specifying the genus and
  1108. * species. The cvterm is also specified using its foreign key and the cv_id
  1109. * for the cvterm is nested as well.
  1110. *
  1111. * @ingroup tripal_chado_api
  1112. */
  1113. function tripal_core_chado_get_foreign_key($table_desc, $field, $values, $options = NULL) {
  1114. // set defaults for options. If we don't set defaults then
  1115. // we get memory leaks when we try to access the elements
  1116. if (!is_array($options)) {
  1117. $options = array();
  1118. }
  1119. if (!array_key_exists('case_insensitive_columns', $options)) {
  1120. $options['case_insensitive_columns'] = array();
  1121. }
  1122. if (!array_key_exists('regex_columns', $options)) {
  1123. $options['regex_columns'] = array();
  1124. }
  1125. // get the list of foreign keys for this table description and
  1126. // iterate through those until we find the one we're looking for
  1127. $fkeys = $table_desc['foreign keys'];
  1128. if ($fkeys) {
  1129. foreach ($fkeys as $name => $def) {
  1130. if (is_array($def['table'])) {
  1131. //foreign key was described 2X
  1132. $message = "The foreign key " . $name . " was defined twice. Please check modules "
  1133. ."to determine if hook_chado_schema_<version>_" . $table_desc['table'] . "() was "
  1134. ."implemented and defined this foreign key when it wasn't supposed to. Modules "
  1135. ."this hook was implemented in: " . implode(', ',
  1136. module_implements("chado_" . $table_desc['table'] . "_schema")) . ".";
  1137. watchdog('tripal_core', $message);
  1138. drupal_set_message(check_plain($message), 'error');
  1139. continue;
  1140. }
  1141. $table = $def['table'];
  1142. $columns = $def['columns'];
  1143. // iterate through the columns of the foreign key relationship
  1144. foreach ($columns as $left => $right) {
  1145. // does the left column in the relationship match our field?
  1146. if (strcmp($field, $left) == 0) {
  1147. // the column name of the foreign key matches the field we want
  1148. // so this is the right relationship. Now we want to select
  1149. $select_cols = array($right);
  1150. $result = tripal_core_chado_select($table, $select_cols, $values, $options);
  1151. $fields = array();
  1152. if ($result and count($result) > 0) {
  1153. foreach ($result as $obj) {
  1154. $fields[] = $obj->$right;
  1155. }
  1156. return $fields;
  1157. }
  1158. }
  1159. }
  1160. }
  1161. }
  1162. else {
  1163. // TODO: what do we do if we get to this point and we have a fk
  1164. // relationship expected but we don't have any definition for one in the
  1165. // table schema??
  1166. $version = tripal_core_get_chado_version(TRUE);
  1167. $message = t("There is no foreign key relationship defined for " . $field . ".
  1168. To define a foreign key relationship, determine the table this foreign
  1169. key referrs to (<foreign table>) and then implement
  1170. hook_chado_chado_schema_v<version>_<foreign table>(). See
  1171. tripal_feature_chado_v1_2_schema_feature for an example. Chado version: $version");
  1172. watchdog('tripal_core', $message);
  1173. drupal_set_message(check_plain($message), 'error');
  1174. }
  1175. return array();
  1176. }
  1177. /**
  1178. * Generates an object containing the full details of a record(s) in chado.
  1179. *
  1180. * This differs from the objects returned by tripal_core_chado_select in so far as all foreign key
  1181. * relationships have been followed meaning you have more complete details. Thus this function
  1182. * should be used whenever you need a full variable and tripal_core_chado_select should be used if
  1183. * you only case about a few columns.
  1184. *
  1185. * @param $table
  1186. * The name of the base table to generate a variable for
  1187. * @param $values
  1188. * A select values array that selects the records you want from the base table
  1189. * (this has the same form as tripal_core_chado_select)
  1190. * @param $base_options
  1191. * An array containing options for the base table. For example, an
  1192. * option of 'order_by' may be used to sort results in the base table
  1193. * if more than one are returned. The options must be compatible with
  1194. * the options accepted by the tripal_core_chado_select() function.
  1195. * @return
  1196. * Either an object (if only one record was selected from the base table)
  1197. * or an array of objects (if more than one record was selected from the base table).
  1198. *
  1199. * Example Usage:
  1200. * @code
  1201. $values = array(
  1202. 'name' => 'Medtr4g030710'
  1203. );
  1204. $features = tripal_core_generate_chado_var('feature', $values);
  1205. * @endcode
  1206. * This will return an object if there is only one feature with the name Medtr4g030710 or it will
  1207. * return an array of feature objects if more than one feature has that name.
  1208. *
  1209. * Note to Module Designers: Fields can be excluded by default from these objects by implementing
  1210. * one of the following hooks:
  1211. * - hook_exclude_field_from_tablename_by_default (where tablename is the name of the table):
  1212. * This hook allows you to add fields to be excluded on a per table basis. Simply implement
  1213. * this hook to return an array of fields to be excluded. For example:
  1214. * @code
  1215. mymodule_exclude_field_from_feature_by_default() {
  1216. return array('residues' => TRUE);
  1217. }
  1218. * @endcode
  1219. * will ensure that feature.residues is ecluded from a feature object by default.
  1220. * - hook_exclude_type_by_default:
  1221. * This hook allows you to exclude fields from all tables that are of a given postgresql field
  1222. * type. Simply implement this hook to return an array of postgresql types mapped to criteria.
  1223. * Then all fields of that type where the criteria supplied returns TRUE will be excluded from
  1224. * any table. Tokens available in criteria are &gt;field_value&lt; and &gt;field_name&lt; . For example:
  1225. * @code
  1226. mymodule_exclude_type_by_default() {
  1227. return array('text' => 'length(&gt;field_value&lt; ) > 50');
  1228. }
  1229. * @endcode
  1230. * 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.
  1231. *
  1232. * @ingroup tripal_chado_api
  1233. */
  1234. function tripal_core_generate_chado_var($table, $values, $base_options = array()) {
  1235. $all = new stdClass();
  1236. // get description for the current table----------------------------------------------------------
  1237. $table_desc = tripal_core_get_chado_table_schema($table);
  1238. $table_primary_key = $table_desc['primary key'][0];
  1239. $table_columns = array_keys($table_desc['fields']);
  1240. // Expandable fields without value needed for criteria--------------------------------------------
  1241. $all->expandable_fields = array();
  1242. if ($table_desc['referring_tables']) {
  1243. $all->expandable_tables = $table_desc['referring_tables'];
  1244. }
  1245. else {
  1246. $all->expandable_tables = array();
  1247. }
  1248. $all->expandable_nodes = array();
  1249. // Get fields to be removed by name.................................
  1250. $fields_to_remove = module_invoke_all('exclude_field_from_' . $table . '_by_default');
  1251. foreach ($fields_to_remove as $field_name => $criteria) {
  1252. //replace &gt;field_name&lt; with the current field name &
  1253. $criteria = preg_replace('/&gt;field_name&lt; /', $field_name, $criteria);
  1254. // if field_value needed we can't deal with this field yet
  1255. if (preg_match('/&gt;field_value&lt; /', $criteria)) {
  1256. break;
  1257. }
  1258. //if criteria then remove from query
  1259. // @coder-ignore: only module designers can populate $criteria -not security risk
  1260. $success = drupal_eval('<?php return ' . $criteria . '; ?>');
  1261. // watchdog('tripal_core',
  1262. // 'Evaluating criteria (%criteria) for field %field in tripal_core_generate_chado_var for %table evaluated to %success',
  1263. // array('%table' => $table, '%criteria'=>$criteria, '%field' => $field_name, '%success'=>$success),
  1264. // WATCHDOG_NOTICE
  1265. // );
  1266. if ($success) {
  1267. unset($table_columns[array_search($field_name, $table_columns)]);
  1268. unset($fields_to_remove[$field_name]);
  1269. $all->expandable_fields[] = $table . '.' . $field_name;
  1270. }
  1271. }
  1272. //Get fields to be removed by type................................
  1273. $types_to_remove = module_invoke_all('exclude_type_by_default');
  1274. $field_types = array();
  1275. foreach ($table_desc['fields'] as $field_name => $field_array) {
  1276. $field_types[$field_array['type']][] = $field_name;
  1277. }
  1278. foreach ($types_to_remove as $field_type => $criteria) {
  1279. // if there are fields of that type to remove
  1280. if (is_array($field_types[$field_type])) {
  1281. //replace &gt;field_name&lt; with the current field name &
  1282. $criteria = preg_replace('/&gt;field_name&lt; /', $field_name, $criteria);
  1283. foreach ($field_types[$field_type] as $field_name) {
  1284. // if field_value needed we can't deal with this field yet
  1285. if (preg_match('/&gt;field_value&lt; /', $criteria)) {
  1286. $fields_to_remove[$field_name] = $criteria;
  1287. continue;
  1288. }
  1289. // if field_value needed we can't deal with this field yet
  1290. if (preg_match('/&gt;field_value&lt; /', $criteria)) {
  1291. break;
  1292. }
  1293. //if criteria then remove from query
  1294. // @coder-ignore: only module designers can populate $criteria -not security risk
  1295. $success = drupal_eval('<?php return ' . $criteria . '; ?>');
  1296. // watchdog('tripal_core',
  1297. // 'Evaluating criteria (%criteria) for field %field of $type in tripal_core_generate_chado_var for %table evaluated to %success',
  1298. // array('%table'=>$table, '%criteria'=>$criteria, '%field'=>$field_name, '%type'=>$field_type, '%success'=>$success),
  1299. // WATCHDOG_NOTICE
  1300. // );
  1301. if ($success) {
  1302. unset($table_columns[array_search($field_name, $table_columns)]);
  1303. $all->expandable_fields[] = $table . '.' . $field_name;
  1304. }
  1305. } //end of foreach field of that type
  1306. }
  1307. } //end of foreach type to be removed
  1308. // get the values for the record in the current table---------------------------------------------
  1309. $results = tripal_core_chado_select($table, $table_columns, $values, $base_options);
  1310. if ($results) {
  1311. foreach ($results as $key => $object) {
  1312. // Add empty expandable_x arrays
  1313. $object->expandable_fields = $all->expandable_fields;
  1314. $object->expandable_tables = $all->expandable_tables;
  1315. $object->expandable_nodes = $all->expandable_nodes;
  1316. // add curent table
  1317. $object->tablename = $table;
  1318. // check if the current table maps to a node type-----------------------------------------------
  1319. // if this table is connected to a node there will be a chado_tablename table in drupal
  1320. if (db_table_exists('chado_' . $table)) {
  1321. // that has a foreign key to this one ($table_desc['primary key'][0]
  1322. // and to the node table (nid)
  1323. $sql = "SELECT %s, nid FROM {chado_%s} WHERE %s=%d";
  1324. $mapping = db_fetch_object(db_query(
  1325. $sql,
  1326. $table_primary_key,
  1327. $table,
  1328. $table_primary_key,
  1329. $object->{$table_primary_key}
  1330. ));
  1331. if ($mapping->{$table_primary_key}) {
  1332. $object->nid = $mapping->nid;
  1333. $object->expandable_nodes[] = $table;
  1334. }
  1335. }
  1336. // remove any fields where criteria need to be evalulated---------------------------------------
  1337. foreach ($fields_to_remove as $field_name => $criteria) {
  1338. if (!isset($object->{$field_name})) {
  1339. break;
  1340. }
  1341. $criteria = preg_replace('/&gt;field_value&lt; /', $object->{$field_name}, $criteria);
  1342. //if criteria then remove from query
  1343. // @coder-ignore: only module designers can populate $criteria -not security risk
  1344. $success = drupal_eval('<?php return ' . $criteria . '; ?>');
  1345. // watchdog('tripal_core',
  1346. // 'Evaluating criteria (%criteria) for field %field in tripal_core_generate_chado_var for %table evaluated to %success',
  1347. // array('%table' => $table, '%criteria'=>$criteria, '%field' => $field_name, '%success'=>$success),
  1348. // WATCHDOG_NOTICE
  1349. // );
  1350. if ($success) {
  1351. unset($object->{$field_name});
  1352. $object->expandable_fields[] = $table . '.' . $field_name;
  1353. }
  1354. }
  1355. // recursively follow foreign key relationships nesting objects as we go------------------------
  1356. if ($table_desc['foreign keys']) {
  1357. foreach ($table_desc['foreign keys'] as $foreign_key_array) {
  1358. $foreign_table = $foreign_key_array['table'];
  1359. foreach ($foreign_key_array['columns'] as $foreign_key => $primary_key) {
  1360. // Note: Foreign key is the field in the current table whereas primary_key is the field in
  1361. // the table referenced by the foreign key
  1362. //Dont do anything if the foreign key is empty
  1363. if (empty($object->{$foreign_key})) {
  1364. break;
  1365. }
  1366. // get the record from the foreign table
  1367. $foreign_values = array($primary_key => $object->{$foreign_key});
  1368. $foreign_object = tripal_core_generate_chado_var($foreign_table, $foreign_values);
  1369. // add the foreign record to the current object in a nested manner
  1370. $object->{$foreign_key} = $foreign_object;
  1371. // Flatten expandable_x arrays so only in the bottom object
  1372. if (is_array($object->{$foreign_key}->expandable_fields)) {
  1373. $object->expandable_fields = array_merge(
  1374. $object->expandable_fields,
  1375. $object->{$foreign_key}->expandable_fields
  1376. );
  1377. unset($object->{$foreign_key}->expandable_fields);
  1378. }
  1379. if (is_array($object->{$foreign_key}->expandable_tables)) {
  1380. $object->expandable_tables = array_merge(
  1381. $object->expandable_tables,
  1382. $object->{$foreign_key}->expandable_tables
  1383. );
  1384. unset($object->{$foreign_key}->expandable_tables);
  1385. }
  1386. if (is_array($object->{$foreign_key}->expandable_nodes)) {
  1387. $object->expandable_nodes = array_merge(
  1388. $object->expandable_nodes,
  1389. $object->{$foreign_key}->expandable_nodes
  1390. );
  1391. unset($object->{$foreign_key}->expandable_nodes);
  1392. }
  1393. }
  1394. }
  1395. $results[$key] = $object;
  1396. }
  1397. }
  1398. }
  1399. // check only one result returned
  1400. if (sizeof($results) == 1) {
  1401. // add results to object
  1402. return $results[0];
  1403. }
  1404. elseif (!empty($results)) {
  1405. return $results;
  1406. }
  1407. else {
  1408. // no results returned
  1409. }
  1410. }
  1411. /**
  1412. * Retrieves fields/tables/nodes that were excluded by default from a variable and adds them
  1413. *
  1414. * This function exists to allow tripal_core_generate_chado_var() to excldue some
  1415. * fields/tables/nodes from the default form of a variable without making it extremely difficult for
  1416. * the tripal admin to get at these variables if he/she wants them.
  1417. *
  1418. * @param $object
  1419. * This must be an object generated using tripal_core_generate_chado_var()
  1420. * @param $type
  1421. * Must be one of 'field', 'table', 'node'. Indicates what is being expanded.
  1422. * @param $to_expand
  1423. * The name of the field/table/node to be expanded
  1424. * @param $table_options
  1425. * An array containing options for the base table. For example, an
  1426. * option of 'order_by' may be used to sort results in the base table
  1427. * if more than one are returned. The options must be compatible with
  1428. * the options accepted by the tripal_core_chado_select() function.
  1429. * @return
  1430. * A chado object supplemented with the field/table/node requested to be expanded
  1431. *
  1432. * Example Usage:
  1433. * @code
  1434. // Get a chado object to be expanded
  1435. $values = array(
  1436. 'name' => 'Medtr4g030710'
  1437. );
  1438. $features = tripal_core_generate_chado_var('feature', $values);
  1439. // Expand the organism node
  1440. $feature = tripal_core_expand_chado_vars($feature, 'node', 'organism');
  1441. // Expand the feature.residues field
  1442. $feature = tripal_core_expand_chado_vars($feature, 'field', 'feature.residues');
  1443. // Expand the feature properties (featureprop table)
  1444. $feature = tripal_core_expand_chado_vars($feature, 'table', 'featureprop');
  1445. * @endcode
  1446. *
  1447. * @ingroup tripal_chado_api
  1448. */
  1449. function tripal_core_expand_chado_vars($object, $type, $to_expand, $table_options = array()) {
  1450. $base_table = $object->tablename;
  1451. // check to see if they are expanding an array of objects
  1452. if (is_array($object)) {
  1453. foreach ($object as $index => $o) {
  1454. $object[$index] = tripal_core_expand_chado_vars($o, $type, $to_expand);
  1455. }
  1456. return $object;
  1457. }
  1458. switch ($type) {
  1459. case "field": //--------------------------------------------------------------------------------
  1460. if (preg_match('/(\w+)\.(\w+)/', $to_expand, $matches)) {
  1461. $tablename = $matches[1];
  1462. $fieldname = $matches[2];
  1463. $table_desc = tripal_core_get_chado_table_schema($tablename);
  1464. $values = array();
  1465. foreach ($table_desc['primary key'] as $key) {
  1466. $values[$key] = $object->{$key};
  1467. }
  1468. if ($base_table == $tablename) {
  1469. //get the field
  1470. $results = tripal_core_chado_select(
  1471. $tablename,
  1472. array($fieldname),
  1473. $values
  1474. );
  1475. $object->{$fieldname} = $results[0]->{$fieldname};
  1476. $object->expanded = $to_expand;
  1477. }
  1478. else {
  1479. //We need to recurse -the field is in a nested object
  1480. foreach ((array) $object as $field_name => $field_value) {
  1481. if (is_object($field_value)) {
  1482. $object->{$field_name} = tripal_core_expand_chado_vars(
  1483. $field_value,
  1484. 'field',
  1485. $to_expand
  1486. );
  1487. }
  1488. } //end of for each field in the current object
  1489. }
  1490. }
  1491. else {
  1492. watchdog(
  1493. 'tripal_core',
  1494. 'tripal_core_expand_chado_vars: Field (%field) not in the right format. It should be <tablename>.<fieldname>',
  1495. WATCHDOG_ERROR
  1496. );
  1497. }
  1498. break;
  1499. case "table": //--------------------------------------------------------------------------------
  1500. $foreign_table = $to_expand;
  1501. $foreign_table_desc = tripal_core_get_chado_table_schema($foreign_table);
  1502. // If it's connected to the base table
  1503. if ($foreign_table_desc['foreign keys'][$base_table]) {
  1504. foreach ($foreign_table_desc['foreign keys'][$base_table]['columns'] as $left => $right) {
  1505. if (!$object->{$right}) {
  1506. break;
  1507. }
  1508. if (is_array($values)) {
  1509. $values = array_merge($values, array($left => $object->{$right}) );
  1510. }
  1511. else {
  1512. $values = array($left => $object->{$right});
  1513. }
  1514. $foreign_object = tripal_core_generate_chado_var(
  1515. $foreign_table,
  1516. array($left => $object->{$right}),
  1517. $table_options
  1518. );
  1519. if ($foreign_object) {
  1520. // in the case where the foreign key relationships exists more
  1521. // than once with the same table we want to alter the
  1522. // array structure
  1523. if (count($foreign_table_desc['foreign keys'][$base_table]['columns']) > 1) {
  1524. if (!is_object($object->{$foreign_table})) {
  1525. $object->{$foreign_table} = new stdClass();
  1526. }
  1527. $object->{$foreign_table}->{$left} = $foreign_object;
  1528. $object->expanded = $to_expand;
  1529. }
  1530. else {
  1531. $object->{$foreign_table} = $foreign_object;
  1532. $object->expanded = $to_expand;
  1533. }
  1534. }
  1535. }
  1536. }
  1537. else {
  1538. //We need to recurse -the table has a relationship to one of the nested objects
  1539. foreach ((array) $object as $field_name => $field_value) {
  1540. // if we have a nested object ->expand the table in it
  1541. if (is_object($field_value)) {
  1542. $object->{$field_name} = tripal_core_expand_chado_vars(
  1543. $field_value,
  1544. 'table',
  1545. $foreign_table
  1546. );
  1547. }
  1548. }
  1549. }
  1550. break;
  1551. case "node": //---------------------------------------------------------------------------------
  1552. //if the node to be expanded is for our base table, then just expand it
  1553. if ($object->tablename == $to_expand) {
  1554. $node = node_load($object->nid);
  1555. if ($node) {
  1556. $object->expanded = $to_expand;
  1557. $node->expandable_fields = $object->expandable_fields;
  1558. unset($object->expandable_fields);
  1559. $node->expandable_tables = $object->expandable_tables;
  1560. unset($object->expandable_tables);
  1561. $node->expandable_nodes = $object->expandable_nodes;
  1562. unset($object->expandable_nodes);
  1563. $node->{$base_table} = $object;
  1564. $object = $node;
  1565. }
  1566. else {
  1567. watchdog(
  1568. 'tripal_core',
  1569. 'tripal_core_expand_chado_vars: No node matches the nid (%nid) supplied.',
  1570. array('%nid' => $object->nid),
  1571. WATCHDOG_ERROR
  1572. );
  1573. } //end of if node
  1574. }
  1575. else {
  1576. //We need to recurse -the node to expand is one of the nested objects
  1577. foreach ((array) $object as $field_name => $field_value) {
  1578. if (is_object($field_value)) {
  1579. $object->{$field_name} = tripal_core_expand_chado_vars(
  1580. $field_value,
  1581. 'node',
  1582. $to_expand
  1583. );
  1584. }
  1585. } //end of for each field in the current object
  1586. }
  1587. break;
  1588. default:
  1589. watchdog('tripal_core',
  1590. 'tripal_core_expand_chado_vars: Unrecognized type (%type). Should be one of "field", "table", "node".',
  1591. array('%type' => $type),
  1592. WATCHDOG_ERROR
  1593. );
  1594. return FALSE;
  1595. }
  1596. //move extended array downwards-------------------------------------------------------------------
  1597. if (!$object->expanded) {
  1598. //if there's no extended field then go hunting for it
  1599. foreach ( (array)$object as $field_name => $field_value) {
  1600. if (is_object($field_value)) {
  1601. if (isset($field_value->expanded)) {
  1602. $object->expanded = $field_value->expanded;
  1603. unset($field_value->expanded);
  1604. }
  1605. }
  1606. }
  1607. }
  1608. //try again becasue now we might have moved it down
  1609. if ($object->expanded) {
  1610. $expandable_name = 'expandable_' . $type . 's';
  1611. if ($object->{$expandable_name}) {
  1612. $key_to_remove = array_search($object->expanded, $object->{$expandable_name});
  1613. unset($object->{$expandable_name}[$key_to_remove]);
  1614. unset($object->expanded);
  1615. }
  1616. else {
  1617. // if there is an expandable array then we've reached the base object
  1618. // if we get here and don't have anything expanded then something went wrong
  1619. // watchdog(
  1620. // 'tripal_core',
  1621. // 'tripal_core_expand_chado_vars: Unable to expand the %type %to_expand',
  1622. // array('%type'=>$type, '%to_expand'=>$to_expand),
  1623. // WATCHDOG_ERROR
  1624. // );
  1625. } //end of it we've reached the base object
  1626. }
  1627. return $object;
  1628. }
  1629. /**
  1630. * Implements hook_exclude_type_by_default()
  1631. *
  1632. * This hooks allows fields of a specified type that match a specified criteria to be excluded by
  1633. * default from any table when tripal_core_generate_chado_var() is called. Keep in mind that if
  1634. * fields are excluded by default they can always be expanded at a later date using
  1635. * tripal_core_expand_chado_vars().
  1636. *
  1637. * Criteria are php strings that evaluate to either TRUE or FALSE. These strings are evaluated using
  1638. * drupal_eval() which suppresses syntax errors and throws watchdog entries of type php. There are
  1639. * also watchdog entries of type tripal_core stating the exact criteria evaluated. Criteria can
  1640. * contain the following tokens:
  1641. * - &gt;field_name&lt;
  1642. * Replaced by the name of the field to be excluded
  1643. * - &gt;field_value&lt;
  1644. * Replaced by the value of the field in the current record
  1645. * Also keep in mind that if your criteria doesn't contain the &gt;field_value&lt; token then it will be
  1646. * evaluated before the query is executed and if the field is excluded it won't be included in the
  1647. * query.
  1648. *
  1649. * @return
  1650. * An array of type => criteria where the type is excluded if the criteria evaluates to TRUE
  1651. *
  1652. * @ingroup tripal_chado_api
  1653. */
  1654. function tripal_core_exclude_type_by_default() {
  1655. return array('text' => "strlen('&gt;field_value&lt; ') > 100");
  1656. }
  1657. /**
  1658. * Implements hook_exclude_field_from_<tablename>_by_default()
  1659. *
  1660. * This hooks allows fields from a specified table that match a specified criteria to be excluded by
  1661. * default from any table when tripal_core_generate_chado_var() is called. Keep in mind that if
  1662. * fields are excluded by default they can always be expanded at a later date using
  1663. * tripal_core_expand_chado_vars().
  1664. *
  1665. * Criteria are php strings that evaluate to either TRUE or FALSE. These strings are evaluated using
  1666. * drupal_eval() which suppresses syntax errors and throws watchdog entries of type php. There are
  1667. * also watchdog entries of type tripal_core stating the exact criteria evaluated. Criteria can
  1668. * contain the following tokens:
  1669. * - &gt;field_name&lt;
  1670. * Replaced by the name of the field to be excluded
  1671. * - &gt;field_value&lt;
  1672. * Replaced by the value of the field in the current record
  1673. * Also keep in mind that if your criteria doesn't contain the &gt;field_value&lt; token then it will be
  1674. * evaluated before the query is executed and if the field is excluded it won't be included in the
  1675. * query.
  1676. *
  1677. * @return
  1678. * An array of type => criteria where the type is excluded if the criteria evaluates to TRUE
  1679. *
  1680. * @ingroup tripal_chado_api
  1681. */
  1682. function tripal_core_exclude_field_from_feature_by_default() {
  1683. return array();
  1684. }
  1685. /**
  1686. * Use this function instead of db_query() to avoid switching databases
  1687. * when making query to the chado database
  1688. *
  1689. * Will use a chado persistent connection if it already exists
  1690. *
  1691. * @param $sql
  1692. * The sql statement to execute
  1693. */
  1694. function chado_query($sql) {
  1695. $args = func_get_args();
  1696. array_shift($args); // remove the $sql from the argument list
  1697. $sql = db_prefix_tables($sql);
  1698. if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
  1699. $args = $args[0];
  1700. }
  1701. _db_query_callback($args, TRUE);
  1702. $sql = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $sql);
  1703. // Execute the query on the chado database/schema
  1704. // Use the persistent chado connection if it already exists
  1705. $persistent_connection = unserialize(variable_get('tripal_perisistent_chado', NULL));
  1706. if ($persistent_connection) {
  1707. $query = $sql;
  1708. // Duplicate the _db_query code in order to ensure that the drupal
  1709. // $active_db variable is never touched
  1710. // thus changed $active_db to $persistent_connection
  1711. // START COPY FROM _db_query in database.pgsql.inc
  1712. if (variable_get('dev_query', 0)) {
  1713. list($usec, $sec) = explode(' ', microtime());
  1714. $timer = (float) $usec + (float) $sec;
  1715. }
  1716. $last_result = pg_query($persistent_connection, $query);
  1717. if (variable_get('dev_query', 0)) {
  1718. $bt = debug_backtrace();
  1719. $query = $bt[2]['function'] . "\n" . $query;
  1720. list($usec, $sec) = explode(' ', microtime());
  1721. $stop = (float) $usec + (float) $sec;
  1722. $diff = $stop - $timer;
  1723. $queries[] = array($query, $diff);
  1724. }
  1725. if ($debug) {
  1726. print '<p>query: ' . $query . '<br />error:' . pg_last_error($persistent_connection) . '</p>';
  1727. }
  1728. if ($last_result !== FALSE) {
  1729. return $last_result;
  1730. }
  1731. else {
  1732. // Indicate to drupal_error_handler that this is a database error.
  1733. ${DB_ERROR} = TRUE;
  1734. trigger_error(check_plain(pg_last_error($persistent_connection) . "\nquery: " . $query), E_USER_WARNING);
  1735. return FALSE;
  1736. }
  1737. // END COPY FROM _db_query in database.pgsql.inc
  1738. }
  1739. else {
  1740. $previous_db = tripal_db_set_active('chado');
  1741. $results = _db_query($sql);
  1742. tripal_db_set_active($previous_db);
  1743. }
  1744. return $results;
  1745. }
  1746. /**
  1747. * Get chado id for a node. E.g, if you want to get 'analysis_id' from the
  1748. * 'analysis' table for a synced 'chado_analysis' node, use:
  1749. * $analysis_id = chado_get_id_for_node ('analysis', $node)
  1750. * Likewise,
  1751. * $organism_id = chado_get_id_for_node ('organism', $node)
  1752. * $feature_id = chado_get_id_for_node ('feature', $node)
  1753. */
  1754. function chado_get_id_for_node($table, $node) {
  1755. return db_result(db_query("SELECT %s_id FROM {chado_%s} WHERE nid = %d", $table, $table, $node->nid));
  1756. }
  1757. /**
  1758. * Get node id for a chado feature/organism/analysis. E.g, if you want to
  1759. * get the node id for an analysis, use:
  1760. * $nid = chado_get_node_id ('analysis', $analysis_id)
  1761. * Likewise,
  1762. * $nid = chado_get_node_id ('organism', $organism_id)
  1763. * $nid = chado_get_node_id ('feature', $feature_id)
  1764. */
  1765. function chado_get_node_id($table, $id) {
  1766. return db_result(db_query("SELECT nid FROM {chado_%s} WHERE %s_id = %d", $table, $table, $id));
  1767. }
  1768. /**
  1769. * Retrieve a property for a given base table record
  1770. *
  1771. * @param $basetable
  1772. * The base table for which the property should be retrieved. Thus to retrieve a property
  1773. * for a feature the basetable=feature and property is retrieved from featureprop
  1774. * @param $record_id
  1775. * The foriegn key field of the base table. This should be in integer.
  1776. * @param $property
  1777. * The cvterm name describing the type of properties to be retrieved
  1778. * @param $cv_name
  1779. * The name of the cv that the above cvterm is part of
  1780. *
  1781. * @return
  1782. * An array in the same format as that generated by the function
  1783. * tripal_core_generate_chado_var(). If only one record is returned it
  1784. * is a single object. If more than one record is returned then it is an array
  1785. * of objects
  1786. *
  1787. * @ingroup tripal_chado_api
  1788. */
  1789. function tripal_core_get_property($basetable, $record_id, $property, $cv_name) {
  1790. // get the foreign key for this property table
  1791. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  1792. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1793. // construct the array of values to be selected
  1794. $values = array(
  1795. $fkcol => $record_id,
  1796. 'type_id' => array(
  1797. 'cv_id' => array(
  1798. 'name' => $cv_name,
  1799. ),
  1800. 'name' => $property,
  1801. 'is_obsolete' => 0
  1802. ),
  1803. );
  1804. $results = tripal_core_generate_chado_var($basetable . 'prop', $values);
  1805. $results = tripal_core_expand_chado_vars($results, 'field', $basetable . 'prop.value');
  1806. return $results;
  1807. }
  1808. /**
  1809. * Insert a property for a given base table. By default if the property already
  1810. * exists a new property is added with the next available rank. If
  1811. * $update_if_present argument is specified then the record will be updated if it
  1812. * exists rather than adding a new property.
  1813. *
  1814. * @param $basetable
  1815. * The base table for which the property should be inserted. Thus to insert a property
  1816. * for a feature the basetable=feature and property is inserted into featureprop
  1817. * @param $record_id
  1818. * The foriegn key field of the base table. This should be in integer.
  1819. * @param $property
  1820. * The cvterm name describing the type of properties to be inserted
  1821. * @param $cv_name
  1822. * The name of the cv that the above cvterm is part of
  1823. * @param $value
  1824. * The value of the property to be inserted (can be empty)
  1825. * @param $update_if_present
  1826. * A boolean indicating whether an existing record should be updated. If the
  1827. * property already exists and this value is not specified or is zero then
  1828. * a new property will be added with the next largest rank.
  1829. *
  1830. * @return
  1831. * Return True on Insert/Update and False otherwise
  1832. *
  1833. * @ingroup tripal_chado_api
  1834. */
  1835. function tripal_core_insert_property($basetable, $record_id, $property,
  1836. $cv_name, $value, $update_if_present = 0) {
  1837. // first see if the property already exists, if the user want's to update
  1838. // then we can do that, but otherwise we want to increment the rank and
  1839. // insert
  1840. $props = tripal_core_get_property($basetable, $record_id, $property, $cv_name);
  1841. if (!is_array($props)) {
  1842. $props = array($props);
  1843. }
  1844. $rank = 0;
  1845. if (count($props)>0) {
  1846. if ($update_if_present) {
  1847. return tripal_core_update_property($basetable, $record_id, $property, $cv_name, $value);
  1848. }
  1849. else {
  1850. // iterate through the properties returned and check to see if the
  1851. // property with this value already exists if not, get the largest rank
  1852. // and insert the same property but with this new value
  1853. foreach ($props as $p) {
  1854. if ($p->rank > $rank) {
  1855. $rank = $p->rank;
  1856. }
  1857. if (strcmp($p->value, $value) == 0) {
  1858. return TRUE;
  1859. }
  1860. }
  1861. // now add 1 to the rank
  1862. $rank++;
  1863. }
  1864. }
  1865. // get the foreign key for this property table
  1866. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  1867. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1868. // construct the array of values to be inserted
  1869. $values = array(
  1870. $fkcol => $record_id,
  1871. 'type_id' => array(
  1872. 'cv_id' => array(
  1873. 'name' => $cv_name,
  1874. ),
  1875. 'name' => $property,
  1876. 'is_obsolete' => 0
  1877. ),
  1878. 'value' => $value,
  1879. 'rank' => $rank,
  1880. );
  1881. return tripal_core_chado_insert($basetable . 'prop', $values);
  1882. }
  1883. /**
  1884. * Update a property for a given base table record and property name. This
  1885. * function should be used only if one record of the property will be present.
  1886. * If the property name can have multiple entries (with increasing rank) then
  1887. * use the function named tripal_core_update_property_by_id
  1888. *
  1889. * @param $basetable
  1890. * The base table for which the property should be updated. The property table
  1891. * is constructed using a combination of the base table name and the suffix
  1892. * 'prop' (e.g. basetable = feature then property tabie is featureprop).
  1893. * @param $record_id
  1894. * The foreign key of the basetable to update a property for. This should be in integer.
  1895. * For example, if the basetable is 'feature' then the $record_id should be the feature_id
  1896. * @param $property
  1897. * The cvterm name of property to be updated
  1898. * @param $cv_name
  1899. * The name of the cv that the above cvterm is part of
  1900. * @param $value
  1901. * The value of the property to be inserted (can be empty)
  1902. * @param $insert_if_missing
  1903. * A boolean indicating whether a record should be inserted if one doesn't exist to update
  1904. *
  1905. * Note: The property to be updated is select via the unique combination of $record_id and
  1906. * $property and then it is updated with the supplied value
  1907. *
  1908. * @return
  1909. * Return True on Update/Insert and False otherwise
  1910. *
  1911. * @ingroup tripal_chado_api
  1912. */
  1913. function tripal_core_update_property($basetable, $record_id, $property,
  1914. $cv_name, $value, $insert_if_missing = 0) {
  1915. // first see if the property is missing (we can't update a missing property
  1916. $prop = tripal_core_get_property($basetable, $record_id, $property, $cv_name);
  1917. if (count($prop)==0) {
  1918. if ($insert_if_missing) {
  1919. return tripal_core_insert_property($basetable, $record_id, $property, $cv_name, $value);
  1920. }
  1921. else {
  1922. return FALSE;
  1923. }
  1924. }
  1925. // get the foreign key for this property table
  1926. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  1927. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1928. // construct the array that will match the exact record to update
  1929. $match = array(
  1930. $fkcol => $record_id,
  1931. 'type_id' => array(
  1932. 'cv_id' => array(
  1933. 'name' => $cv_name,
  1934. ),
  1935. 'name' => $property,
  1936. ),
  1937. );
  1938. // construct the array of values to be updated
  1939. $values = array(
  1940. 'value' => $value,
  1941. );
  1942. return tripal_core_chado_update($basetable . 'prop', $match, $values);
  1943. }
  1944. /**
  1945. * Update a property for a given base table record. This function should be
  1946. * used if multiple records of the same property will be present. Also, use this
  1947. * function to change the property name of an existing property.
  1948. *
  1949. * @param $basetable
  1950. * The base table for which the property should be updated. The property table
  1951. * is constructed using a combination of the base table name and the suffix
  1952. * 'prop' (e.g. basetable = feature then property tabie is featureprop).
  1953. * @param $record_id
  1954. * The primary key of the base table. This should be in integer.
  1955. * For example, if the basetable is 'feature' then the $record_id should be the featureprop_id
  1956. * @param $property
  1957. * The cvterm name of property to be updated
  1958. * @param $cv_name
  1959. * The name of the cv that the above cvterm is part of
  1960. * @param $value
  1961. * The value of the property to be inserted (can be empty)
  1962. *
  1963. * @return
  1964. * Return True on Update/Insert and False otherwise
  1965. *
  1966. * @ingroup tripal_chado_api
  1967. */
  1968. function tripal_core_update_property_by_id($basetable, $record_id, $property,
  1969. $cv_name, $value) {
  1970. // get the primary key for this property table
  1971. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  1972. $pkcol = $table_desc['primary key'][0];
  1973. // construct the array that will match the exact record to update
  1974. $match = array(
  1975. $pkcol => $record_id,
  1976. );
  1977. // construct the array of values to be updated
  1978. $values = array(
  1979. 'type_id' => array(
  1980. 'cv_id' => array(
  1981. 'name' => $cv_name,
  1982. ),
  1983. 'name' => $property,
  1984. ),
  1985. 'value' => $value,
  1986. );
  1987. return tripal_core_chado_update($basetable . 'prop', $match, $values);
  1988. }
  1989. /**
  1990. * Deletes a property for a given base table record using the property name
  1991. *
  1992. * @param $basetable
  1993. * The base table for which the property should be deleted. Thus to deleted a property
  1994. * for a feature the basetable=feature and property is deleted from featureprop
  1995. * @param $record_id
  1996. * The primary key of the basetable to delete a property for. This should be in integer.
  1997. * @param $property
  1998. * The cvterm name describing the type of property to be deleted
  1999. * @param $cv_name
  2000. * The name of the cv that the above cvterm is part of
  2001. *
  2002. * Note: The property to be deleted is select via the unique combination of $record_id and $property
  2003. *
  2004. * @return
  2005. * Return True on Delete and False otherwise
  2006. *
  2007. * @ingroup tripal_chado_api
  2008. */
  2009. function tripal_core_delete_property($basetable, $record_id, $property, $cv_name) {
  2010. // get the foreign key for this property table
  2011. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  2012. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  2013. // construct the array that will match the exact record to update
  2014. $match = array(
  2015. $fkcol => $record_id,
  2016. 'type_id' => array(
  2017. 'cv_id' => array(
  2018. 'name' => $cv_name,
  2019. ),
  2020. 'name' => $property,
  2021. ),
  2022. );
  2023. return tripal_core_chado_delete($basetable . 'prop', $match);
  2024. }
  2025. /**
  2026. * Deletes a property using the property ID
  2027. *
  2028. * @param $basetable
  2029. * The base table for which the property should be deleted. Thus to deleted a property
  2030. * for a feature the basetable=feature and property is deleted from featureprop
  2031. * @param $record_id
  2032. * The primary key of the basetable to delete a property for. This should be in integer.
  2033. *
  2034. * @return
  2035. * Return True on Delete and False otherwise
  2036. *
  2037. * @ingroup tripal_chado_api
  2038. */
  2039. function tripal_core_delete_property_by_id($basetable, $record_id) {
  2040. // get the foreign key for this property table
  2041. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  2042. $pkcol = $table_desc['primary key'][0];
  2043. // construct the array that will match the exact record to update
  2044. $match = array(
  2045. $pkcol => $record_id,
  2046. );
  2047. return tripal_core_chado_delete($basetable . 'prop', $match);
  2048. }
  2049. /**
  2050. * This function is typically used in the '.install' file for a Tripal module
  2051. * Each module should call this function during installation to create
  2052. * the module data directory which is sites/default/files/tripal/[module_name]
  2053. * for default Drupal settings. This directory can then be used by the module
  2054. * for storing files.
  2055. *
  2056. * @param $module_name
  2057. * the name of the module being installed.
  2058. *
  2059. * @returns
  2060. * nothing
  2061. *
  2062. * @ingroup tripal_files_api
  2063. */
  2064. function tripal_create_moddir($module_name) {
  2065. // make the data directory for this module
  2066. $data_dir = file_directory_path() . "/tripal/$module_name";
  2067. if (!file_check_directory($data_dir, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
  2068. $message = "Cannot create directory $data_dir. This module may not ".
  2069. "behave correctly without this directory. Please create ".
  2070. "the directory manually or fix the problem and reinstall.";
  2071. drupal_set_message(check_plain(t($message)), 'error');
  2072. watchdog('tripal_core', $message, array(), WATCHDOG_ERROR);
  2073. }
  2074. }
  2075. /**
  2076. * Each Tripal module has a unique data directory which was creatd using the
  2077. * tripal_create_moddir function during installation. This function
  2078. * retrieves the directory path.
  2079. *
  2080. * @param $module_name
  2081. * The name of the module
  2082. *
  2083. * @returns
  2084. * The path within the Drupal installation where the data directory resides
  2085. * @ingroup tripal_files_api
  2086. */
  2087. function tripal_get_moddir($module_name) {
  2088. $data_dir = file_directory_path() . "/tripal/$module_name";
  2089. return $data_dir;
  2090. }
  2091. /**
  2092. * Set the Tripal Database
  2093. *
  2094. * The tripal_db_set_active function is used to prevent namespace collisions
  2095. * when chado and drupal are installed in the same database but in different
  2096. * schemas. It is also used for backwards compatibility with older versions
  2097. * of tripal or in cases where chado is located outside of the Drupal database.
  2098. *
  2099. * @ingroup tripal_chado_api
  2100. */
  2101. function tripal_db_set_active($dbname) {
  2102. global $db_url, $db_type;
  2103. $chado_exists = 0;
  2104. // only postgres can support search paths. So if this is MysQL then
  2105. // just run the normal tripal_db_set_active function.
  2106. if (strcmp($db_type, 'pgsql')==0) {
  2107. // if the 'chado' database is in the $db_url variable then chado is
  2108. // not in the same Drupal database
  2109. if (is_array($db_url)) {
  2110. if (isset($db_url[$dbname])) {
  2111. return db_set_active($dbname);
  2112. }
  2113. }
  2114. // check to make sure the chado schema exists
  2115. $chado_exists = tripal_core_chado_schema_exists();
  2116. // here we make the assumption that the default database schema is
  2117. // 'public'. This will most likely always be the case but if not,
  2118. // then this code will break
  2119. if ($chado_exists && strcmp($dbname, 'chado')==0) {
  2120. db_query("set search_path to %s", 'chado,public');
  2121. return 'public,chado';
  2122. }
  2123. elseif ($chado_exists) {
  2124. db_query("set search_path to %s", 'public,chado');
  2125. return 'chado,public';
  2126. }
  2127. else {
  2128. return db_set_active($dbname);
  2129. }
  2130. }
  2131. else {
  2132. return db_set_active($dbname);
  2133. }
  2134. }
  2135. /**
  2136. * Indicates if the SQL statement is prepapred
  2137. *
  2138. * @param $statement_name
  2139. * The name of the statement to check if it is prepared.
  2140. *
  2141. * @return
  2142. * TRUE if the statement is preapred, FALSE otherwise
  2143. */
  2144. function tripal_core_is_sql_prepared($statement_name) {
  2145. // to reduce the need for a database query we will check the
  2146. // session variable for this connection to see if the statement
  2147. // has been prepared. If it has then we won't do the database
  2148. // query to find out. If it hasn't then we'll query the database
  2149. // to see if it is prepared.
  2150. $connection = variable_get('tripal_perisistent_chado', NULL);
  2151. if (!isset($_SESSION[$connection])) {
  2152. $_SESSION[$connection] = array();
  2153. }
  2154. if(in_array($statement_name,$_SESSION[$connection])){
  2155. //print "Is Prepared and in Session var: $statement_name\n";
  2156. return TRUE;
  2157. }
  2158. // @coder-ignore: acting on postgres tables rather then drupal schema therefore, table prefixing does not apply
  2159. $sql = "SELECT name FROM pg_prepared_statements WHERE name = '%s'";
  2160. // do not use 'chado_query' here or it causes memory-leaks
  2161. $result = db_fetch_object(db_query($sql, $statement_name));
  2162. if ($result) {
  2163. $_SESSION[$connection][] = $statement_name;
  2164. //print "Is Prepared but in DB: $statement_name\n";
  2165. return TRUE;
  2166. }
  2167. //print "Is Not prepared: $statement_name\n";
  2168. return FALSE;
  2169. }
  2170. /**
  2171. * Instantiate or Return a persistent chado connection
  2172. *
  2173. * NOTE: cannot use $active_db since a new connection is created each time
  2174. * db_set_active() is called
  2175. *
  2176. * @return
  2177. * A postgresql connection object which can be used by pg_prepare, pg_execute, etc.
  2178. */
  2179. function tripal_db_persistent_chado() {
  2180. global $db_url;
  2181. // get connection if it already exists
  2182. // Otherwise we need to set it
  2183. $connection = unserialize(variable_get('tripal_perisistent_chado', NULL));
  2184. if ($connection) {
  2185. return $connection;
  2186. }
  2187. else {
  2188. if (is_array($db_url) && isset($db_url['chado'])) {
  2189. $connection = db_connect($db_url['chado']);
  2190. variable_set('tripal_perisistent_chado', $connection);
  2191. }
  2192. else {
  2193. $connection = db_connect($db_url);
  2194. variable_set('tripal_perisistent_chado', serialize($connection));
  2195. }
  2196. return $connection;
  2197. }
  2198. return FALSE;
  2199. }
  2200. /**
  2201. * Release a persistent chado connection
  2202. */
  2203. function tripal_db_release_persistent_chado() {
  2204. variable_del('tripal_perisistent_chado');
  2205. }
  2206. /**
  2207. * Start a transaction block. Ensures the use of a persistent chado connection
  2208. */
  2209. function tripal_db_start_transaction() {
  2210. $connection = tripal_db_persistent_chado();
  2211. chado_query("BEGIN");
  2212. }
  2213. /**
  2214. * Set a savepoint to roll the current transaction back to if an error is encountered
  2215. */
  2216. function tripal_db_set_savepoint_transaction($savepoint, $release = FALSE) {
  2217. // Postgresql requires a savepoint of the same name to be unset before re-use
  2218. if ($release) {
  2219. chado_query("RELEASE SAVEPOINT %s", $savepoint);
  2220. }
  2221. chado_query("SAVEPOINT %s", $savepoint);
  2222. }
  2223. /**
  2224. * Commit changes made during the current transaction
  2225. */
  2226. function tripal_db_commit_transaction() {
  2227. chado_query("COMMIT");
  2228. }
  2229. /**
  2230. * Rollback changes.
  2231. *
  2232. * If $savepoint is NULL then rollback to the beginning of the transaction,
  2233. * Otherwise, rollback to the point at which the named $savepoint was created
  2234. *
  2235. * @param $savepoint
  2236. * The name of the saved point in the transaction to rollback to
  2237. */
  2238. function tripal_db_rollback_transaction($savepoint = NULL, $commit = TRUE) {
  2239. if ($savepoint) {
  2240. chado_query("ROLLBACK TO SAVEPOINT %s", $savepoint);
  2241. }
  2242. else {
  2243. chado_query("ROLLBACK");
  2244. }
  2245. if ($commit) {
  2246. tripal_db_commit_transaction();
  2247. }
  2248. }
  2249. /**
  2250. * Purpose: Get max rank for a given set of criteria
  2251. * This function was developed with the many property tables in chado in mind
  2252. *
  2253. * @param $tablename
  2254. * The name of the chado table you want to select the max rank from this table must contain a
  2255. * rank column of type integer
  2256. * @param $where_options
  2257. * where options should include the id and type for that table to correctly
  2258. * group a set of records together where the only difference are the value and rank
  2259. * @code
  2260. * array(
  2261. * <column_name> => array(
  2262. * 'type' => <type of column: INT/STRING>,
  2263. * 'value' => <the value you want to filter on>,
  2264. * 'exact' => <if TRUE use =; if FALSE use ~>,
  2265. * )
  2266. * )
  2267. * @endcode
  2268. * @return the maximum rank
  2269. *
  2270. * @ingroup tripal_chado_api
  2271. */
  2272. function tripal_get_max_chado_rank($tablename, $where_options) {
  2273. $where= array();
  2274. //generate the where clause from supplied options
  2275. // the key is the column name
  2276. foreach ($where_options as $key => $val_array) {
  2277. if (preg_match('/INT/', $val_array['type'])) {
  2278. $where[] = $key . "=" . $val_array['value'];
  2279. }
  2280. else {
  2281. if ($val_array['exact']) {
  2282. $operator='=';
  2283. }
  2284. else {
  2285. $operator='~';
  2286. }
  2287. $where[] = $key . $operator . "'" . $val_array['value'] . "'";
  2288. }
  2289. }
  2290. $previous_db = tripal_db_set_active('chado');
  2291. $result = db_fetch_object(db_query(
  2292. "SELECT max(rank) as max_rank, count(rank) as count FROM %s WHERE %s",
  2293. $tablename,
  2294. implode(' AND ', $where)
  2295. ));
  2296. tripal_db_set_active($previous_db);
  2297. //drupal_set_message("Max Rank Query=SELECT max(rank) as max_rank, count(rank) as count FROM ".$tablename." WHERE ".implode(' AND ',$where));
  2298. if ($result->count > 0) {
  2299. return $result->max_rank;
  2300. }
  2301. else {
  2302. return -1;
  2303. }
  2304. }
  2305. /**
  2306. * Add a new table to the Chado schema. This function is simply a wrapper for
  2307. * the db_create_table() function of Drupal, but ensures the table is created
  2308. * inside the Chado schema rather than the Drupal schema. If the table already
  2309. * exists then it will be dropped and recreated using the schema provided.
  2310. * Howver, it will only drop a table if it exsits in the tripal_custom_tables
  2311. * table. This way the function cannot be used to accidentally alter existing
  2312. * non custom tables.
  2313. *
  2314. * @param $ret
  2315. * Array to which query results will be added.
  2316. * @param $table
  2317. * The name of the table to create.
  2318. * @param $schema
  2319. * A Drupal-style Schema API definition of the table
  2320. *
  2321. * @return
  2322. * A database query result resource for the new table, or FALSE if table was not constructed.
  2323. *
  2324. * @ingroup tripal_core_api
  2325. */
  2326. function tripal_create_chado_table(&$ret, $table, $schema) {
  2327. $ret = array();
  2328. // If the table exits in Chado but not in the tripal_custom_tables field
  2329. // then call an error. if the table exits in the tripal_custom_tables but
  2330. // not in Chado then create the table and replace the entry.
  2331. $sql = "SELECT * FROM {tripal_custom_tables} WHERE table_name = '%s'";
  2332. $centry = db_fetch_object(db_query($sql, $table));
  2333. $previous_db = tripal_db_set_active('chado'); // use chado database
  2334. $exists = db_table_exists($table);
  2335. tripal_db_set_active($previous_db); // now use drupal database
  2336. if (!$exists) {
  2337. $previous_db = tripal_db_set_active('chado'); // use chado database
  2338. db_create_table($ret, $table, $schema);
  2339. tripal_db_set_active($previous_db); // now use drupal database
  2340. if (count($ret)==0) {
  2341. watchdog('tripal_core', "Error adding custom table '!table_name'.",
  2342. array('!table_name' => $table), WATCHDOG_ERROR);
  2343. return FALSE;
  2344. }
  2345. }
  2346. if ($exists and !$centry) {
  2347. watchdog('tripal_core', "Could not add custom table '!table_name'. It ".
  2348. "already exists but is not known to Tripal as being a custom table.",
  2349. array('!table_name' => $table), WATCHDOG_WARNING);
  2350. return FALSE;
  2351. }
  2352. if ($exists and $centry) {
  2353. // drop the table we'll recreate it with the new schema
  2354. $previous_db = tripal_db_set_active('chado'); // use chado database
  2355. db_drop_table($ret, $table);
  2356. db_create_table($ret, $table, $schema);
  2357. tripal_db_set_active($previous_db); // now use drupal database
  2358. }
  2359. // if the table creation was succesful then add an entry
  2360. // in the tripal_custom_table
  2361. $record = new stdClass();
  2362. $record->table_name = $table;
  2363. $record->schema = serialize($schema);
  2364. // if an entry already exists then remove it
  2365. if ($centry) {
  2366. $sql = "DELETE FROM {tripal_custom_tables} WHERE table_name = '%s'";
  2367. db_query($sql, $table);
  2368. }
  2369. $success = drupal_write_record('tripal_custom_tables', $record);
  2370. if (!$success) {
  2371. watchdog('tripal_core', "Error adding custom table.",
  2372. array('!table_name' => $table), WATCHDOG_ERROR);
  2373. return FALSE;
  2374. }
  2375. return $ret;
  2376. }
  2377. /**
  2378. * Retrieves the schema in an array for the specified custom table.
  2379. *
  2380. * @param $table
  2381. * The name of the table to create.
  2382. *
  2383. * @return
  2384. * A Drupal-style Schema API array definition of the table. Returns
  2385. * FALSE on failure.
  2386. *
  2387. * @ingroup tripal_core_api
  2388. */
  2389. function tripal_get_chado_custom_schema($table) {
  2390. $sql = "SELECT schema FROM {tripal_custom_tables} WHERE table_name = '%s'";
  2391. $custom = db_fetch_object(db_query($sql, $table));
  2392. if (!$custom) {
  2393. return FALSE;
  2394. }
  2395. else {
  2396. return unserialize($custom->schema);
  2397. }
  2398. }
  2399. /**
  2400. * Check that the Chado schema exists
  2401. *
  2402. * @return
  2403. * TRUE/FALSE depending upon whether it exists
  2404. */
  2405. function tripal_core_chado_schema_exists() {
  2406. // This is postgresql-specific code to check the existence of the chado schema
  2407. // @coder-ignore: acting on pg_catalog schema rather then drupal schema therefore, table prefixing does not apply
  2408. $sql = "SELECT nspname FROM pg_catalog.pg_namespace WHERE nspname = 'chado'";
  2409. if (db_fetch_object(db_query($sql))) {
  2410. return TRUE;
  2411. }
  2412. else {
  2413. return FALSE;
  2414. }
  2415. }
  2416. /**
  2417. * Retrieves the list tables in the Chado schema. By default it only retursn
  2418. * the default Chado tables, but may also return custom tables added to the
  2419. * Chado schema as well.
  2420. *
  2421. * @param $include_custom
  2422. * Optional. Set as TRUE to include any custom tables created in the
  2423. * Chado schema. Custom tables are added to Chado using the
  2424. * tripal_core_chado_create_table() function.
  2425. *
  2426. * @returns
  2427. * An associative array where the key and value pairs are the Chado table names.
  2428. *
  2429. * @ingroup tripal_core_api
  2430. */
  2431. function tripal_core_get_chado_tables($include_custom = NULL) {
  2432. if (is_array($db_url) AND array_key_exists('chado', $db_url)) {
  2433. $previous_db = tripal_db_set_active('chado');
  2434. // @coder-ignore: acting on pg_catalog schema rather then drupal schema therefore, table prefixing does not apply
  2435. $sql = 'SELECT tablename FROM pg_tables';
  2436. $resource = db_query($sql);
  2437. tripal_db_set_active($previous_db);
  2438. }
  2439. else {
  2440. // @coder-ignore: acting on pg_catalog schema rather then drupal schema therefore, table prefixing does not apply
  2441. $sql = "SELECT tablename FROM pg_tables WHERE schemaname='chado'";
  2442. $resource = db_query($sql);
  2443. }
  2444. $tables = array();
  2445. while ($r = db_fetch_object($resource)) {
  2446. $tables[$r->tablename] = $r->tablename;
  2447. }
  2448. // now add in the custom tables too
  2449. if ($include_custom) {
  2450. $sql = "SELECT table_name FROM {tripal_custom_tables}";
  2451. $resource = db_query($sql);
  2452. }
  2453. while ($r = db_fetch_object($resource)) {
  2454. $tables[$r->table_name] = $r->table_name;
  2455. }
  2456. asort($tables);
  2457. return $tables;
  2458. }
  2459. /**
  2460. * Sets a Drupal variable with the current version of Chado. This variable
  2461. * can then be queried later using the tripal_core_get_chado_Version
  2462. *
  2463. * @returns
  2464. * The version of Chado
  2465. *
  2466. * @ingroup tripal_core_api
  2467. */
  2468. function tripal_core_set_chado_version() {
  2469. // check that Chado is installed if not return 'uninstalled as the version'
  2470. $chado_exists = tripal_core_chado_schema_exists();
  2471. if (!$chado_exists) {
  2472. return 'not installed';
  2473. }
  2474. // if the table doesn't exist then we don't know what version but we know
  2475. // it must be 1.11 or older.
  2476. $previous_db = tripal_db_set_active('chado');
  2477. $prop_exists = db_table_exists('chadoprop');
  2478. tripal_db_set_active($previous_db);
  2479. if (!$prop_exists) {
  2480. return "1.11 or older";
  2481. }
  2482. // we can't use the Tripal API to query this table
  2483. // because the Tripal API depends on this fucntion to
  2484. // tell it the version. So, we need a typical SQL statement
  2485. $sql = "SELECT value "
  2486. ."FROM chadoprop CP "
  2487. ." INNER JOIN cvterm CVT on CVT.cvterm_id = CP.type_id "
  2488. ." INNER JOIN cv CV on CVT.cv_id = CV.cv_id "
  2489. ."WHERE CV.name = 'chado_properties' and CVT.name = 'version'";
  2490. $previous_db = tripal_db_set_active('chado');
  2491. $v = db_fetch_object(db_query($sql));
  2492. $previous_db = tripal_db_set_active('chado');
  2493. // if we don't have a version in the chadoprop table then it must be
  2494. // v1.11 or older
  2495. if (!$v->value) {
  2496. variable_set('chado_version', "1.11 or older");
  2497. return "1.11 or older";
  2498. }
  2499. variable_set('chado_version', $v->value);
  2500. return $v->value;
  2501. }
  2502. /**
  2503. * Returns the version number of the currently installed Chado instance.
  2504. * It can return the real or effective version.
  2505. *
  2506. * @param $exact
  2507. * Set this argument to 1 to retrieve the exact version that is installed.
  2508. * Otherwise, this function will set the version to the nearest 'tenth'.
  2509. * Chado versioning numbers in the hundreds represent changes to the
  2510. * software and not the schema. Changes in the tenth's represent changes
  2511. * in the schema.
  2512. *
  2513. * @param $warn_if_unsupported
  2514. * If the currently installed version of Chado is not supported by Tripal
  2515. * the generatea a Drupal warning.
  2516. *
  2517. * @returns
  2518. * The version of Chado
  2519. *
  2520. * @ingroup tripal_core_api
  2521. */
  2522. function tripal_core_get_chado_version($exact = FALSE, $warn_if_unsupported = FALSE) {
  2523. // first get the chado version that is installed
  2524. $exact_version = variable_get('chado_version', '');
  2525. if (!$exact_version) {
  2526. $exact_version = tripal_core_set_chado_version();
  2527. }
  2528. // Tripal only supports v1.11 or newer.. really this is the same as v1.1
  2529. // but at the time the v1.11 schema API was written we didn't know that so
  2530. // we'll return the version 1.11 so the schema API will work.
  2531. if (strcmp($exact_version, '1.11 or older') == 0) {
  2532. $exact_version = "1.11";
  2533. if($warn_if_unsupported){
  2534. drupal_set_message(t("WARNING: Tripal does not fully support Chado version less than v1.1. If you are certain this is v1.1
  2535. of if Chado was installed using an earlier version of Tripal then all is well. If not please upgrade to v1.1 or later"),
  2536. 'warning');
  2537. }
  2538. }
  2539. // if not returing an exact version, return the version to the nearest 10th.
  2540. // return 1.2 for all versions of 1.2x
  2541. $effective_version = $exact_version;
  2542. if (preg_match('/^1\.2\d+$/', $effective_version)){
  2543. $effective_version = "1.2";
  2544. }
  2545. if ($warn_if_unsupported and ($effective_version != 1.11 and $effective_version != 1.2)) {
  2546. drupal_set_message(t("WARNING: The currently installed version of Chado, v$exact_version, is not fully compatible with Tripal."),'warning');
  2547. }
  2548. // if the callee has requested the exact version then return it
  2549. if ($exact) {
  2550. return $exact_version;
  2551. }
  2552. return $effective_version;
  2553. }
  2554. /**
  2555. * Retrieves the chado tables Schema API array.
  2556. *
  2557. * @param $table
  2558. * The name of the table to retrieve. The function will use the appopriate
  2559. * Tripal chado schema API hooks (e.g. v1.11 or v1.2).
  2560. *
  2561. * @returns
  2562. * A Drupal Schema API array defining the table.
  2563. *
  2564. * @ingroup tripal_core_api
  2565. */
  2566. function tripal_core_get_chado_table_schema($table) {
  2567. // first get the chado version that is installed
  2568. $v = tripal_core_get_chado_version();
  2569. // get the table array from the proper chado schema
  2570. $v = preg_replace("/\./", "_", $v); // reformat version for hook name
  2571. $table_arr = module_invoke_all("chado_schema_v" . $v . "_" . $table);
  2572. return $table_arr;
  2573. }