tripal_core.api.inc 132 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587
  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. * - return_record: by default, the function will return the record but with
  86. * the primary keys added after insertion. To simply return TRUE on success
  87. * set this option to FALSE
  88. *
  89. * @return
  90. * On success this function returns the inserted record with the new primary keys
  91. * add to the returned array. On failure, it returns FALSE.
  92. *
  93. * Example usage:
  94. * @code
  95. * $values = array(
  96. * 'organism_id' => array(
  97. * 'genus' => 'Citrus',
  98. * 'species' => 'sinensis',
  99. * ),
  100. * 'name' => 'orange1.1g000034m.g',
  101. * 'uniquename' => 'orange1.1g000034m.g',
  102. * 'type_id' => array (
  103. * 'cv_id' => array (
  104. * 'name' => 'sequence',
  105. * ),
  106. * 'name' => 'gene',
  107. * 'is_obsolete' => 0
  108. * ),
  109. * );
  110. * $result = tripal_core_chado_insert('feature',$values);
  111. * @endcode
  112. * The above code inserts a record into the feature table. The $values array is
  113. * nested such that the organism is selected by way of the organism_id foreign
  114. * key constraint by specifying the genus and species. The cvterm is also
  115. * specified using its foreign key and the cv_id for the cvterm is nested as
  116. * well.
  117. *
  118. * @ingroup tripal_chado_api
  119. */
  120. function tripal_core_chado_insert($table, $values, $options = array()) {
  121. // set defaults for options. If we don't set defaults then
  122. // we get memory leaks when we try to access the elements
  123. if (!is_array($options)) {
  124. $options = array();
  125. }
  126. if (!array_key_exists('is_prepared', $options)) {
  127. $options['is_prepared'] = FALSE;
  128. }
  129. if (!array_key_exists('statement_name', $options)) {
  130. $options['statement_name'] = FALSE;
  131. }
  132. if (!array_key_exists('skip_validation', $options)) {
  133. $options['skip_validation'] = FALSE;
  134. }
  135. if (!array_key_exists('return_record', $options)) {
  136. $options['return_record'] = TRUE;
  137. }
  138. $insert_values = array();
  139. // Determine plan of action
  140. if ($options['statement_name']) {
  141. // we have a prepared statment (or want to create one) so set $prepared = TRUE
  142. $prepared = TRUE;
  143. // we need to get a persistent connection. If one exists this function
  144. // will not recreate it, but if not it will create one and store it in
  145. // a Drupal variable for reuse later.
  146. $connection = tripal_db_persistent_chado();
  147. // if we cannot get a connection the abandon the prepared statement
  148. if (!$connection) {
  149. $prepared = FALSE;
  150. unset($options['statement_name']);
  151. }
  152. }
  153. else {
  154. //print "NO STATEMENT (insert): $table\n";
  155. //debug_print_backtrace();
  156. }
  157. if (array_key_exists('skip_validation', $options)) {
  158. $validate = !$options['skip_validation'];
  159. }
  160. else {
  161. $validate = TRUE;
  162. }
  163. // get the table description
  164. $table_desc = tripal_core_get_chado_table_schema($table);
  165. if (empty($table_desc)) {
  166. watchdog('tripal_core', 'tripal_core_chado_insert: There is no table description for !table_name', array('!table_name' => $table), WATCHDOG_WARNING);
  167. }
  168. // iterate through the values array and create a new 'insert_values' array
  169. // that has all the values needed for insert with all foreign relationsihps
  170. // resolved.
  171. foreach ($values as $field => $value) {
  172. // make sure the field is in the table description. If not then return an error
  173. // message
  174. if (!array_key_exists($field, $table_desc['fields'])) {
  175. watchdog('tripal_core', "tripal_core_chado_insert: The field '%field' does not exist ".
  176. "for the table '%table'. Cannot perform insert. Values: %array",
  177. array('%field' => $field, '%table' => $table, '%array' => print_r($values, 1)), WATCHDOG_ERROR);
  178. return FALSE;
  179. }
  180. if (is_array($value)) {
  181. $foreign_options = array();
  182. if ($options['statement_name']) {
  183. // add the fk relationship info to the prepared statement name so that
  184. // we can prepare the selects run by the recrusive tripal_core_chado_get_foreign_key
  185. // function.
  186. $fk_sname = "fk_" . $table . "_" . $field;
  187. foreach ($value as $k => $v) {
  188. $fk_sname .= substr($k, 0, 2);
  189. }
  190. $foreign_options['statement_name'] = $fk_sname;
  191. }
  192. // select the value from the foreign key relationship for this value
  193. $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value, $foreign_options);
  194. if (sizeof($results) > 1) {
  195. 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);
  196. }
  197. elseif (sizeof($results) < 1) {
  198. //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);
  199. }
  200. else {
  201. $insert_values[$field] = $results[0];
  202. }
  203. }
  204. else {
  205. $insert_values[$field] = $value;
  206. }
  207. }
  208. if ($validate) {
  209. // check for violation of any unique constraints
  210. $ukeys = array();
  211. if (array_key_exists('unique keys', $table_desc)) {
  212. $ukeys = $table_desc['unique keys'];
  213. }
  214. $ukselect_cols = array();
  215. $ukselect_vals = array();
  216. if ($ukeys) {
  217. foreach ($ukeys as $name => $fields) {
  218. foreach ($fields as $index => $field) {
  219. // build the arrays for performing a select that will check the contraint
  220. $ukselect_cols[] = $field;
  221. if (!array_key_exists($field, $insert_values)) {
  222. if (array_key_exists('default', $table_desc['fields'][$field])) {
  223. $ukselect_vals[$field] = $table_desc['fields'][$field]['default'];
  224. }
  225. }
  226. else {
  227. $ukselect_vals[$field] = $insert_values[$field];
  228. }
  229. }
  230. // now check the constraint
  231. $coptions = array();
  232. if ($options['statement_name']) {
  233. $coptions = array('statement_name' => 'uqsel_' . $table . '_' . $name);
  234. }
  235. if (tripal_core_chado_select($table, $ukselect_cols, $ukselect_vals, $coptions)) {
  236. watchdog('tripal_core', "tripal_core_chado_insert: Cannot insert duplicate record into $table table: " .
  237. print_r($values, 1), array(), 'WATCHDOG_ERROR');
  238. return FALSE;
  239. }
  240. }
  241. }
  242. // if trying to insert a field that is the primary key, make sure it also is unique
  243. if (array_key_exists('primary key', $table_desc)) {
  244. $pkey = $table_desc['primary key'][0];
  245. if (array_key_exists($pkey, $insert_values)) {
  246. $coptions = array('statement_name' => 'pqsel_' . $table . '_' . $pkey);
  247. if (tripal_core_chado_select($table, array($pkey), array($pkey => $insert_values[$pkey]), $coptions)) {
  248. watchdog('tripal_core', "tripal_core_chado_insert: Cannot insert duplicate primary key into $table table: " . print_r($values, 1), array(), 'WATCHDOG_ERROR');
  249. return FALSE;
  250. }
  251. }
  252. }
  253. // make sure required fields have a value
  254. if (!is_array($table_desc['fields'])) {
  255. $table_desc['fields'] = array();
  256. watchdog('tripal_core', "tripal_core_chado_insert: %table missing fields: \n %schema",
  257. array('%table' => $table, '%schema' => print_r($table_desc, 1)), WATCHDOG_WARNING);
  258. }
  259. foreach ($table_desc['fields'] as $field => $def) {
  260. // a field is considered missing if it cannot be NULL and there is no default
  261. // value for it or it is of type 'serial'
  262. if (array_key_exists('NOT NULL', $def) and
  263. !array_key_exists($field, $insert_values) and
  264. !array_key_exists('default', $def) and
  265. strcmp($def['type'], serial) != 0) {
  266. watchdog('tripal_core', "tripal_core_chado_insert: Field $table.$field cannot be NULL: " .
  267. print_r($values, 1), array(), 'WATCHDOG_ERROR');
  268. return FALSE;
  269. }
  270. }
  271. } //end of validation
  272. // Now build the insert SQL statement
  273. $ifields = array(); // contains the names of the fields
  274. $ivalues = array(); // contains the values of the fields
  275. $itypes = array(); // contains %d/%s placeholders for the sql query
  276. $iplaceholders = array(); // contains $1/$2 placeholders for the prepare query
  277. $idatatypes = array(); // contains the data type of the fields (int, text, etc.)
  278. $i = 1;
  279. foreach ($insert_values as $field => $value) {
  280. $ifields[] = $field;
  281. $ivalues[] = $value;
  282. $iplaceholders[] = '$' . $i;
  283. $i++;
  284. if (strcmp($value, '__NULL__')==0) {
  285. $itypes[] = "NULL";
  286. $idatatypes[] = "NULL";
  287. }
  288. elseif (strcasecmp($table_desc['fields'][$field]['type'], 'serial')==0 OR
  289. strcasecmp($table_desc['fields'][$field]['type'], 'int')==0 OR
  290. strcasecmp($table_desc['fields'][$field]['type'], 'integer')==0) {
  291. $itypes[] = "%d";
  292. $idatatypes[] = 'int';
  293. }
  294. elseif (strcasecmp($table_desc['fields'][$field]['type'], 'boolean')==0) {
  295. $itypes[] = "%s";
  296. $idatatypes[] = 'bool';
  297. }
  298. elseif (strcasecmp($table_desc['fields'][$field]['type'], 'float')==0) {
  299. $itypes[] = "%s";
  300. $idatatypes[] = 'numeric';
  301. }
  302. else {
  303. $itypes[] = "'%s'";
  304. $idatatypes[] = 'text';
  305. }
  306. }
  307. // create the SQL
  308. $sql = "INSERT INTO {$table} (" . implode(", ", $ifields) . ") VALUES (" . implode(", ", $itypes) . ")";
  309. // if this is a prepared statement then execute it
  310. if ($prepared) {
  311. // if this is the first time we've run this query
  312. // then we need to do the prepare, otherwise just execute
  313. if ($options['is_prepared'] != TRUE) {
  314. // prepare the statement
  315. $psql = "PREPARE " . $options['statement_name'] . " (" . implode(', ', $idatatypes) . ") AS INSERT INTO {$table} (" . implode(", ", $ifields) . ") VALUES (" . implode(", ", $iplaceholders) . ")";
  316. $status = tripal_core_chado_prepare($options['statement_name'], $psql, $idatatypes);
  317. if (!$status) {
  318. watchdog('tripal_core', "tripal_core_chado_insert: not able to prepare '%name' statement for: %sql", array('%name' => $options['statement_name'], '%sql' => $sql), WATCHDOG_ERROR);
  319. return FALSE;
  320. }
  321. }
  322. $sql = "EXECUTE " . $options['statement_name'] . "(" . implode(", ", $itypes) . ")";
  323. $result = tripal_core_chado_execute_prepared($options['statement_name'], $sql, $ivalues);
  324. }
  325. // if it's not a prepared statement then insert normally
  326. else {
  327. $result = chado_query($sql, $ivalues);
  328. }
  329. // if we have a result then add primary keys to return array
  330. if ($options['return_record'] == TRUE and $result) {
  331. if (array_key_exists('primary key', $table_desc) and is_array($table_desc['primary key'])) {
  332. foreach ($table_desc['primary key'] as $field) {
  333. $sql = '';
  334. $psql = "PREPARE currval_" . $table . "_" . $field . " AS SELECT CURRVAL('" . $table . "_" . $field . "_seq')";
  335. $is_prepared = tripal_core_chado_prepare("currval_" . $table . "_" . $field, $psql, array());
  336. $value = '';
  337. if ($is_prepared) {
  338. $value = db_result(chado_query("EXECUTE currval_". $table . "_" . $field));
  339. if (!$value) {
  340. watchdog('tripal_core', "tripal_core_chado_insert: not able to retrieve primary key after insert: %sql",
  341. array('%sql' => $psql), WATCHDOG_ERROR);
  342. return FALSE;
  343. }
  344. }
  345. else {
  346. $sql = "SELECT CURRVAL('" . $table . "_" . $field . "_seq')";
  347. $value = db_result(chado_query($sql));
  348. if (!$value) {
  349. watchdog('tripal_core', "tripal_core_chado_insert: not able to retrieve primary key after insert: %sql",
  350. array('%sql' => $sql), WATCHDOG_ERROR);
  351. return FALSE;
  352. }
  353. }
  354. $values[$field] = $value;
  355. }
  356. }
  357. return $values;
  358. }
  359. elseif ($options['return_record'] == FALSE and $result) {
  360. return TRUE;
  361. }
  362. else {
  363. watchdog('tripal_core', "tripal_core_chado_insert: Cannot insert record into $table table: " . print_r($values, 1), array(), 'WATCHDOG_ERROR');
  364. return FALSE;
  365. }
  366. return FALSE;
  367. }
  368. /**
  369. * Provides a generic routine for updating into any Chado table
  370. *
  371. * Use this function to update a record in any Chado table. The first
  372. * argument specifies the table for inserting, the second is an array
  373. * of values to matched for locating the record for updating, and the third
  374. * argument give the values to update. The arrays are mutli-dimensional such
  375. * that foreign key lookup values can be specified.
  376. *
  377. * @param $table
  378. * The name of the chado table for inserting
  379. * @param $match
  380. * An associative array containing the values for locating a record to update.
  381. * @param $values
  382. * An associative array containing the values for updating.
  383. * @param $options
  384. * An array of options such as:
  385. * - statement_name: the name of the prepared statement to use. If the statement
  386. * has not yet been prepared it will be prepared automatically. On subsequent
  387. * calls with the same statement_name only an execute on the previously
  388. * prepared statement will occur.
  389. * - is_prepared: TRUE or FALSE. Whether or not the statement is prepared. By
  390. * default if the statement is not prepared it will be automatically.
  391. * However to avoid this check, which requires a database query you can
  392. * set this value to true and the check will not be performed.
  393. * - return_record: by default, the function will return the TRUE if the record
  394. * was succesfully updated. However, set this option to TRUE to return the
  395. * record that was updated. The returned record will have the fields provided
  396. * but the primary key (if available for the table) will be added to the record.
  397. * @return
  398. * On success this function returns TRUE. On failure, it returns FALSE.
  399. *
  400. * Example usage:
  401. * @code
  402. $umatch = array(
  403. 'organism_id' => array(
  404. 'genus' => 'Citrus',
  405. 'species' => 'sinensis',
  406. ),
  407. 'uniquename' => 'orange1.1g000034m.g7',
  408. 'type_id' => array (
  409. 'cv_id' => array (
  410. 'name' => 'sequence',
  411. ),
  412. 'name' => 'gene',
  413. 'is_obsolete' => 0
  414. ),
  415. );
  416. $uvalues = array(
  417. 'name' => 'orange1.1g000034m.g',
  418. 'type_id' => array (
  419. 'cv_id' => array (
  420. 'name' => 'sequence',
  421. ),
  422. 'name' => 'mRNA',
  423. 'is_obsolete' => 0
  424. ),
  425. );
  426. * $result = tripal_core_chado_update('feature',$umatch,$uvalues);
  427. * @endcode
  428. * The above code species that a feature with a given uniquename, organism_id,
  429. * and type_id (the unique constraint for the feature table) will be updated.
  430. * The organism_id is specified as a nested array that uses the organism_id
  431. * foreign key constraint to lookup the specified values to find the exact
  432. * organism_id. The same nested struture is also used for specifying the
  433. * values to update. The function will find the record that matches the
  434. * columns specified and update the record with the avlues in the $uvalues array.
  435. *
  436. * @ingroup tripal_chado_api
  437. */
  438. function tripal_core_chado_update($table, $match, $values, $options = NULL) {
  439. // set defaults for options. If we don't set defaults then
  440. // we get memory leaks when we try to access the elements
  441. if (!is_array($options)) {
  442. $options = array();
  443. }
  444. if (!array_key_exists('is_prepared', $options)) {
  445. $options['is_prepared'] = FALSE;
  446. }
  447. if (!array_key_exists('statement_name', $options)) {
  448. $options['statement_name'] = FALSE;
  449. }
  450. if (!array_key_exists('return_record', $options)) {
  451. $options['return_record'] = FALSE;
  452. }
  453. $update_values = array(); // contains the values to be updated
  454. $update_matches = array(); // contains the values for the where clause
  455. // Determine plan of action
  456. if ($options['statement_name']) {
  457. // we have a prepared statment (or want to create one) so set $prepared = TRUE
  458. $prepared = TRUE;
  459. // we need to get a persistent connection. If one exists this function
  460. // will not recreate it, but if not it will create one and store it in
  461. // a Drupal variable for reuse later.
  462. $connection = tripal_db_persistent_chado();
  463. // if we cannot get a connection the abandon the prepared statement
  464. if (!$connection ) {
  465. $prepared = FALSE;
  466. unset($options['statement_name']);
  467. }
  468. }
  469. else {
  470. //print "NO STATEMENT (update): $table\n";
  471. //debug_print_backtrace();
  472. }
  473. // get the table description
  474. $table_desc = tripal_core_get_chado_table_schema($table);
  475. // if the user wants us to return the record then we need to get the
  476. // unique primary key if one exists. That way we can add it to the
  477. // values that get returned at the end of the function
  478. $pkeys = array();
  479. if ($options['return_record'] == TRUE) {
  480. if (array_key_exists('primary key', $table_desc) and is_array($table_desc['primary key'])) {
  481. $columns = array();
  482. $stmt_suffix = '';
  483. foreach ($table_desc['primary key'] as $field) {
  484. $columns[] = $field;
  485. $stmt_suffix .= substr($field, 0, 2);
  486. }
  487. $options2 = array('statement_name' => 'sel_' . $table . '_' . $stmt_suffix);
  488. $results = tripal_core_chado_select($table, $columns, $match, $options2);
  489. if (count($results) > 0) {
  490. foreach ($results as $index => $pkey) {
  491. $pkeys[] = $pkey;
  492. }
  493. }
  494. }
  495. }
  496. // get the values needed for matching in the SQL statement
  497. foreach ($match as $field => $value) {
  498. if (is_array($value)) {
  499. $foreign_options = array();
  500. if ($options['statement_name']) {
  501. // add the fk relationship info to the prepared statement name so that
  502. // we can prepare the selects run by the recrusive tripal_core_chado_get_foreign_key
  503. // function.
  504. $fk_sname = "fk_" . $table . "_" . $field;
  505. foreach ($value as $k => $v) {
  506. $fk_sname .= substr($k, 0, 2);
  507. }
  508. $foreign_options['statement_name'] = $fk_sname;
  509. }
  510. $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value, $foreign_options);
  511. if (sizeof($results) > 1) {
  512. 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);
  513. }
  514. elseif (sizeof($results) < 1) {
  515. //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);
  516. }
  517. else {
  518. $update_matches[$field] = $results[0];
  519. }
  520. }
  521. else {
  522. $update_matches[$field] = $value;
  523. }
  524. }
  525. // get the values used for updating
  526. foreach ($values as $field => $value) {
  527. if (is_array($value)) {
  528. $foreign_options = array();
  529. // select the value from the foreign key relationship for this value
  530. if ($options['statement_name']) {
  531. // add the fk relationship info to the prepared statement name so that
  532. // we can prepare the selects run by the recrusive tripal_core_chado_get_foreign_key
  533. // function.
  534. $fk_sname = "fk_" . $table . "_" . $field;
  535. foreach ($value as $k => $v) {
  536. $fk_sname .= substr($k, 0, 2);
  537. }
  538. $foreign_options['statement_name'] = $fk_sname;
  539. }
  540. $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value, $foreign_options);
  541. if (sizeof($results) > 1) {
  542. 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);
  543. }
  544. elseif (sizeof($results) < 1) {
  545. //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);
  546. }
  547. else {
  548. $update_values[$field] = $results[0];
  549. }
  550. }
  551. else {
  552. $update_values[$field] = $value;
  553. }
  554. }
  555. // now build the SQL statement
  556. $sql = "UPDATE {$table} SET ";
  557. $psql = "UPDATE {$table} SET ";
  558. $uargs = array();
  559. $idatatypes = array();
  560. $pvalues = array();
  561. $ivalues = array();
  562. $i = 1;
  563. foreach ($update_values as $field => $value) {
  564. if (strcasecmp($table_desc['fields'][$field]['type'], 'serial')==0 OR
  565. strcasecmp($table_desc['fields'][$field]['type'], 'int')==0 OR
  566. strcasecmp($table_desc['fields'][$field]['type'], 'integer')==0) {
  567. if (strcmp($value, '__NULL__') == 0) {
  568. $sql .= " $field = %s, ";
  569. $ivalues[] = 'NULL';
  570. $pvalues[] = '%s';
  571. $uargs[] = 'NULL';
  572. }
  573. else {
  574. $sql .= " $field = %d, ";
  575. $ivalues[] = $value;
  576. $pvalues[] = '%d';
  577. $uargs[] = $value;
  578. }
  579. $idatatypes[] = 'int';
  580. }
  581. elseif (strcasecmp($table_desc['fields'][$field]['type'], 'boolean')==0) {
  582. $sql .= " $field = %s, ";
  583. $pvalues[] = '%s';
  584. if (strcmp($value, '__NULL__')==0) {
  585. $ivalues[] = 'NULL';
  586. $uargs[] = 'NULL';
  587. }
  588. else {
  589. $ivalues[] = $value;
  590. $uargs[] = $value;
  591. }
  592. $idatatypes[] = 'bool';
  593. }
  594. elseif (strcasecmp($table_desc['fields'][$field]['type'], 'float')==0) {
  595. $sql .= " $field = %s, ";
  596. $pvalues[] = '%s';
  597. if (strcmp($value, '__NULL__')==0) {
  598. $ivalues[] = 'NULL';
  599. $uargs[] = 'NULL';
  600. }
  601. else {
  602. $ivalues[] = $value;
  603. $uargs[] = $value;
  604. }
  605. $idatatypes[] = 'numeric';
  606. }
  607. else {
  608. if (strcmp($value, '__NULL__') == 0) {
  609. $sql .= " $field = %s, ";
  610. $ivalues[] = 'NULL';
  611. $uargs[] = 'NULL';
  612. $pvalues[] = '%s';
  613. }
  614. else {
  615. $sql .= " $field = '%s', ";
  616. $ivalues[] = $value;
  617. $uargs[] = $value;
  618. $pvalues[] = "'%s'";
  619. }
  620. $idatatypes[] = 'text';
  621. }
  622. $psql .= "$field = \$" . $i . ", ";
  623. $i++;
  624. }
  625. $sql = drupal_substr($sql, 0, -2); // get rid of the trailing comma & space
  626. $psql = drupal_substr($psql, 0, -2); // get rid of the trailing comma & space
  627. $sql .= " WHERE ";
  628. $psql .= " WHERE ";
  629. foreach ($update_matches as $field => $value) {
  630. if (strcasecmp($table_desc['fields'][$field]['type'], 'serial')==0 OR
  631. strcasecmp($table_desc['fields'][$field]['type'], 'int')==0 OR
  632. strcasecmp($table_desc['fields'][$field]['type'], 'integer')==0) {
  633. if (strcmp($value, '__NULL__')==0) {
  634. $sql .= " $field = %s AND ";
  635. $ivalues[] = 'NULL';
  636. $uargs[] = 'NULL';
  637. $pvalues[] = '%s';
  638. }
  639. else {
  640. $sql .= " $field = %d AND ";
  641. $ivalues[] = $value;
  642. $uargs[] = $value;
  643. $pvalues[] = '%s';
  644. }
  645. $idatatypes[] = 'int';
  646. }
  647. elseif (strcasecmp($table_desc['fields'][$field]['type'], 'boolean')==0) {
  648. $sql .= " $field = %s AND ";
  649. $pvalues[] = '%s';
  650. if (strcmp($value, '__NULL__')==0) {
  651. $ivalues[] = 'NULL';
  652. $uargs[] = 'NULL';
  653. }
  654. else {
  655. $ivalues[] = $value;
  656. $uargs[] = $value;
  657. }
  658. $idatatypes[] = 'bool';
  659. }
  660. elseif (strcasecmp($table_desc['fields'][$field]['type'], 'float')==0) {
  661. $sql .= " $field = %s AND ";
  662. $pvalues[] = '%s';
  663. if (strcmp($value, '__NULL__')==0) {
  664. $ivalues[] = 'NULL';
  665. $uargs[] = 'NULL';
  666. }
  667. else {
  668. $ivalues[] = $value;
  669. $uargs[] = $value;
  670. }
  671. $idatatypes[] = 'numeric';
  672. }
  673. else {
  674. if (strcmp($value, '__NULL__')==0) {
  675. $sql .= " $field = %s AND ";
  676. $ivalues[] = 'NULL';
  677. $uargs[] = 'NULL';
  678. $pvalues[] = '%s';
  679. }
  680. else {
  681. $sql .= " $field = '%s' AND ";
  682. $ivalues[] = $value;
  683. $uargs[] = $value;
  684. $pvalues[] = "'%s'";
  685. }
  686. $idatatypes[] = 'text';
  687. }
  688. $psql .= "$field = \$" . $i . " AND ";
  689. $i++;
  690. }
  691. $sql = drupal_substr($sql, 0, -4); // get rid of the trailing 'AND'
  692. $psql = drupal_substr($psql, 0, -4); // get rid of the trailing 'AND'
  693. // finish constructing the prepared SQL statement
  694. $psql = "PREPARE " . $options['statement_name'] . " (" . implode(', ', $idatatypes) . ") AS " . $psql;
  695. // finally perform the update. If successful, return the updated record
  696. if ($prepared) {
  697. // if this is the first time we've run this query
  698. // then we need to do the prepare, otherwise just execute
  699. if ($options['is_prepared'] != TRUE and !tripal_core_is_sql_prepared($options['statement_name'])) {
  700. $status = chado_query($psql);
  701. if (!$status) {
  702. watchdog('tripal_core', "tripal_core_chado_update: not able to prepare '%name' statement for: %sql",
  703. array('%name' => $options['statement_name'], '%sql' => $sql), WATCHDOG_ERROR);
  704. return FALSE;
  705. }
  706. }
  707. $sql = "EXECUTE " . $options['statement_name'] . "(" . implode(", ", $pvalues) . ")";
  708. $result = chado_query($sql, $ivalues);
  709. }
  710. // if it's not a prepared statement then insert normally
  711. else {
  712. $result = chado_query($sql, $uargs);
  713. }
  714. // if we have a result then add primary keys to return array
  715. if ($options['return_record'] == TRUE and $result) {
  716. // only if we have a single result do we want to add the primary keys to the values
  717. // array. If the update matched many records we can't add the pkeys
  718. if (count($pkeys) == 1) {
  719. foreach ($pkeys as $index => $pkey) {
  720. foreach ($pkey as $field => $fvalue) {
  721. $values[$field] = $fvalue;
  722. }
  723. }
  724. }
  725. return $values;
  726. }
  727. elseif ($options['return_record'] == FALSE and $result) {
  728. return TRUE;
  729. }
  730. else {
  731. watchdog('tripal_core', "Cannot update record in $table table. \nMatch:" . print_r($match, 1) . "\nValues: ". print_r($values, 1), array(), 'WATCHDOG_ERROR');
  732. return FALSE;
  733. }
  734. return FALSE;
  735. }
  736. /**
  737. * Provides a generic function for deleting a record(s) from any chado table
  738. *
  739. * Use this function to delete a record(s) in any Chado table. The first
  740. * argument specifies the table to delete from and the second is an array
  741. * of values to match for locating the record(s) to be deleted. The arrays
  742. * are mutli-dimensional such that foreign key lookup values can be specified.
  743. *
  744. * @param $table
  745. * The name of the chado table for inserting
  746. * @param $match
  747. * An associative array containing the values for locating a record to update.
  748. * @param $options
  749. * An array of options such as:
  750. * - statement_name: the name of the prepared statement to use. If the statement
  751. * has not yet been prepared it will be prepared automatically. On subsequent
  752. * calls with the same statement_name only an execute on the previously
  753. * prepared statement will occur.
  754. * - is_prepared: TRUE or FALSE. Whether or not the statement is prepared. By
  755. * default if the statement is not prepared it will be automatically.
  756. * However to avoid this check, which requires a database query you can
  757. * set this value to true and the check will not be performed.
  758. * @return
  759. * On success this function returns TRUE. On failure, it returns FALSE.
  760. *
  761. * Example usage:
  762. * @code
  763. $umatch = array(
  764. 'organism_id' => array(
  765. 'genus' => 'Citrus',
  766. 'species' => 'sinensis',
  767. ),
  768. 'uniquename' => 'orange1.1g000034m.g7',
  769. 'type_id' => array (
  770. 'cv_id' => array (
  771. 'name' => 'sequence',
  772. ),
  773. 'name' => 'gene',
  774. 'is_obsolete' => 0
  775. ),
  776. );
  777. $uvalues = array(
  778. 'name' => 'orange1.1g000034m.g',
  779. 'type_id' => array (
  780. 'cv_id' => array (
  781. 'name' => 'sequence',
  782. ),
  783. 'name' => 'mRNA',
  784. 'is_obsolete' => 0
  785. ),
  786. );
  787. * $result = tripal_core_chado_update('feature',$umatch,$uvalues);
  788. * @endcode
  789. * The above code species that a feature with a given uniquename, organism_id,
  790. * and type_id (the unique constraint for the feature table) will be deleted.
  791. * The organism_id is specified as a nested array that uses the organism_id
  792. * foreign key constraint to lookup the specified values to find the exact
  793. * organism_id. The same nested struture is also used for specifying the
  794. * values to update. The function will find all records that match the
  795. * columns specified and delete them.
  796. *
  797. * @ingroup tripal_chado_api
  798. */
  799. function tripal_core_chado_delete($table, $match, $options = NULL) {
  800. // set defaults for options. If we don't set defaults then
  801. // we get memory leaks when we try to access the elements
  802. if (!is_array($options)) {
  803. $options = array();
  804. }
  805. if (!array_key_exists('is_prepared', $options)) {
  806. $options['is_prepared'] = FALSE;
  807. }
  808. if (!array_key_exists('statement_name', $options)) {
  809. $options['statement_name'] = FALSE;
  810. }
  811. // Determine plan of action
  812. if ($options['statement_name']) {
  813. // we have a prepared statment (or want to create one) so set $prepared = TRUE
  814. $prepared = TRUE;
  815. // we need to get a persistent connection. If one exists this function
  816. // will not recreate it, but if not it will create one and store it in
  817. // a Drupal variable for reuse later.
  818. $connection = tripal_db_persistent_chado();
  819. // if we cannot get a connection the abandon the prepared statement
  820. if (!$connection ) {
  821. $prepared = FALSE;
  822. unset($options['statement_name']);
  823. }
  824. }
  825. else {
  826. //print "NO STATEMENT (update): $table\n";
  827. //debug_print_backtrace();
  828. }
  829. $delete_matches = array(); // contains the values for the where clause
  830. // get the table description
  831. $table_desc = tripal_core_get_chado_table_schema($table);
  832. $fields = $table_desc['fields'];
  833. // get the values needed for matching in the SQL statement
  834. foreach ($match as $field => $value) {
  835. if (is_array($value)) {
  836. // if the user has specified an array of values to delete rather than
  837. // FK relationships the keep those in our match
  838. if (array_values($value) === $value) {
  839. $delete_matches[$field] = $value;
  840. }
  841. else {
  842. $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value);
  843. if (sizeof($results) > 1) {
  844. 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);
  845. }
  846. elseif (sizeof($results) < 1) {
  847. //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);
  848. }
  849. else {
  850. $delete_matches[$field] = $results[0];
  851. }
  852. }
  853. }
  854. else {
  855. $delete_matches[$field] = $value;
  856. }
  857. }
  858. // now build the SQL statement
  859. $sql = "DELETE FROM {$table} WHERE ";
  860. $psql = $sql;
  861. $uargs = array();
  862. $idatatypes = array();
  863. $pvalues = array();
  864. $ivalues = array();
  865. $dargs = array();
  866. $void_prepared = 0;
  867. $i = 1;
  868. foreach ($delete_matches as $field => $value) {
  869. // if we have an array values then this is an "IN" clasue.
  870. // we cannot use prepared statements with these
  871. if (count($value) > 1) {
  872. $sql .= "$field IN (" . db_placeholders($value, 'varchar') . ") AND ";
  873. foreach ($value as $v) {
  874. $dargs[] = $v;
  875. }
  876. $void_prepared = 1;
  877. continue;
  878. }
  879. if (strcasecmp($table_desc['fields'][$field]['type'], 'serial') == 0 OR
  880. strcasecmp($table_desc['fields'][$field]['type'], 'int') == 0 OR
  881. strcasecmp($table_desc['fields'][$field]['type'], 'integer') == 0) {
  882. if (strcmp($value, '__NULL__') == 0) {
  883. $sql .= " $field = NULL AND ";
  884. $ivalues[] = 'NULL';
  885. $pvalues[] = '%s';
  886. $uargs[] = 'NULL';
  887. }
  888. else {
  889. $sql .= " $field = %d AND ";
  890. $ivalues[] = $value;
  891. $pvalues[] = '%d';
  892. $uargs[] = $value;
  893. }
  894. $idatatypes[] = 'int';
  895. }
  896. elseif (strcasecmp($table_desc['fields'][$field]['type'], 'boolean')==0) {
  897. $sql .= " $field = %s AND ";
  898. $pvalues[] = '%s';
  899. if (strcmp($value, '__NULL__')==0) {
  900. $ivalues[] = 'NULL';
  901. $uargs[] = 'NULL';
  902. }
  903. else {
  904. $ivalues[] = $value;
  905. $uargs[] = $value;
  906. }
  907. $idatatypes[] = 'bool';
  908. }
  909. elseif (strcasecmp($table_desc['fields'][$field]['type'], 'float')==0) {
  910. $sql .= " $field = %s AND ";
  911. $pvalues[] = '%s';
  912. if (strcmp($value, '__NULL__')==0) {
  913. $ivalues[] = 'NULL';
  914. $uargs[] = 'NULL';
  915. }
  916. else {
  917. $ivalues[] = $value;
  918. $uargs[] = $value;
  919. }
  920. $idatatypes[] = 'numeric';
  921. }
  922. else {
  923. if (strcmp($value, '__NULL__')==0) {
  924. $sql .= " $field = %s AND ";
  925. $ivalues[] = 'NULL';
  926. $uargs[] = 'NULL';
  927. $pvalues[] = '%s';
  928. }
  929. else {
  930. $sql .= " $field = '%s' AND ";
  931. $ivalues[] = $value;
  932. $uargs[] = $value;
  933. $pvalues[] = "'%s'";
  934. }
  935. $idatatypes[] = 'text';
  936. }
  937. array_push($dargs, $value);
  938. $psql .= "$field = \$" . $i . " AND ";
  939. $i++;
  940. }
  941. $sql = drupal_substr($sql, 0, -4); // get rid of the trailing 'AND'
  942. $psql = drupal_substr($psql, 0, -4); // get rid of the trailing 'AND'
  943. // finish constructing the prepared SQL statement
  944. $psql = "PREPARE " . $options['statement_name'] . " (" . implode(', ', $idatatypes) . ") AS " . $psql;
  945. // finally perform the update. If successful, return the updated record
  946. if ($prepared and !$void_prepared) {
  947. // if this is the first time we've run this query
  948. // then we need to do the prepare, otherwise just execute
  949. if ($options['is_prepared'] != TRUE and
  950. !tripal_core_is_sql_prepared($options['statement_name'])) {
  951. $status = chado_query($psql);
  952. if (!$status) {
  953. watchdog('tripal_core', "tripal_core_chado_delete: not able to prepare '%name' statement for: %sql", array('%name' => $options['statement_name'], '%sql' => $sql), WATCHDOG_ERROR);
  954. return FALSE;
  955. }
  956. }
  957. $sql = "EXECUTE " . $options['statement_name'] . "(" . implode(", ", $pvalues) . ")";
  958. $resource = chado_query($sql, $ivalues);
  959. }
  960. // if it's not a prepared statement then insert normally
  961. else {
  962. $resource = chado_query($sql, $uargs);
  963. }
  964. // finally perform the delete. If successful, return the updated record
  965. $result = chado_query($sql, $dargs);
  966. if ($result) {
  967. return TRUE;
  968. }
  969. else {
  970. watchdog('tripal_core', "Cannot delete record in $table table. Match:" . print_r($match, 1) . ". Values: ". print_r($values, 1), array(), 'WATCHDOG_ERROR');
  971. return FALSE;
  972. }
  973. return FALSE;
  974. }
  975. /**
  976. * Provides a generic routine for selecting data from a Chado table
  977. *
  978. * Use this function to perform a simple select from any Chado table.
  979. *
  980. * @param $table
  981. * The name of the chado table for inserting
  982. * @param $columns
  983. * An array of column names
  984. * @param $values
  985. * An associative array containing the values for filtering the results. In the
  986. * case where multiple values for the same time are to be selected an additional
  987. * entry for the field should appear for each value
  988. * @param $options
  989. * An associative array of additional options where the key is the option
  990. * and the value is the value of that option.
  991. *
  992. * Additional Options Include:
  993. * - has_record
  994. * Set this argument to 'TRUE' to have this function return a numeric
  995. * value for the number of recrods rather than the array of records. this
  996. * can be useful in 'if' statements to check the presence of particula records.
  997. * - return_sql
  998. * Set this to 'TRUE' to have this function return an array where the first
  999. * element is the sql that would have been run and the second is an array of
  1000. * arguments.
  1001. * - case_insensitive_columns
  1002. * An array of columns to do a case insensitive search on.
  1003. * - regex_columns
  1004. * An array of columns where the value passed in should be treated as a regular expression
  1005. * - order_by
  1006. * An associative array containing the column names of the table as keys
  1007. * and the type of sort (i.e. ASC, DESC) as the values. The results in the
  1008. * query will be sorted by the key values in the direction listed by the value
  1009. * - statement_name: the name of the prepared statement to use. If the statement
  1010. * has not yet been prepared it will be prepared automatically. On subsequent
  1011. * calls with the same statement_name only an execute on the previously
  1012. * prepared statement will occur.
  1013. * - is_prepared: TRUE or FALSE. Whether or not the statement is prepared. By
  1014. * default if the statement is not prepared it will be automatically.
  1015. * However to avoid this check, which requires a database query you can
  1016. * set this value to true and the check will not be performed.
  1017. * - is_duplicate: TRUE or FALSE. Checks the values submited to see if
  1018. * they violate any of the unique constraints. If so, the record
  1019. * is returned, if not, FALSE is returned.
  1020. *
  1021. *
  1022. * @return
  1023. * A database query result resource, FALSE if the query was not executed
  1024. * correctly, an empty array if no records were matched, or the number of records
  1025. * in the dataset if $has_record is set.
  1026. * If the option 'is_duplicate' is provided and the record is a duplicate it
  1027. * will return the duplicated record. If the 'has_record' option is provided
  1028. * a value of TRUE will be returned if a record exists and FALSE will bee
  1029. * returned if there are not records.
  1030. *
  1031. * Example usage:
  1032. * @code
  1033. * $columns = array('feature_id', 'name');
  1034. * $values = array(
  1035. * 'organism_id' => array(
  1036. * 'genus' => 'Citrus',
  1037. * 'species' => array('sinensis', 'clementina'),
  1038. * ),
  1039. * 'uniquename' => 'orange1.1g000034m.g',
  1040. * 'type_id' => array (
  1041. * 'cv_id' => array (
  1042. * 'name' => 'sequence',
  1043. * ),
  1044. * 'name' => 'gene',
  1045. * 'is_obsolete' => 0
  1046. * ),
  1047. * );
  1048. * $options = array(
  1049. * 'statement_name' => 'sel_feature_genus_species_cvname'
  1050. * 'order_by' => array(
  1051. * 'name' => 'ASC'
  1052. * ),
  1053. * );
  1054. * $result = tripal_core_chado_select('feature',$columns,$values,$options);
  1055. * @endcode
  1056. * The above code selects a record from the feature table using the three fields
  1057. * that uniquely identify a feature. The $columns array simply lists the columns
  1058. * to select. The $values array is nested such that the organism is identified by
  1059. * way of the organism_id foreign key constraint by specifying the genus and
  1060. * species. The cvterm is also specified using its foreign key and the cv_id
  1061. * for the cvterm is nested as well. In the example above, two different species
  1062. * are allowed to match
  1063. *
  1064. * @ingroup tripal_chado_api
  1065. */
  1066. function tripal_core_chado_select($table, $columns, $values, $options = NULL) {
  1067. // set defaults for options. If we don't set defaults then
  1068. // we get memory leaks when we try to access the elements
  1069. if (!is_array($options)) {
  1070. $options = array();
  1071. }
  1072. if (!array_key_exists('case_insensitive_columns', $options)) {
  1073. $options['case_insensitive_columns'] = array();
  1074. }
  1075. if (!array_key_exists('regex_columns', $options)) {
  1076. $options['regex_columns'] = array();
  1077. }
  1078. if (!array_key_exists('order_by', $options)) {
  1079. $options['order_by'] = array();
  1080. }
  1081. if (!array_key_exists('is_prepared', $options)) {
  1082. $options['is_prepared'] = FALSE;
  1083. }
  1084. if (!array_key_exists('return_sql', $options)) {
  1085. $options['return_sql'] = FALSE;
  1086. }
  1087. if (!array_key_exists('has_record', $options)) {
  1088. $options['has_record'] = FALSE;
  1089. }
  1090. if (!array_key_exists('statement_name', $options)) {
  1091. $options['statement_name'] = FALSE;
  1092. }
  1093. if (!array_key_exists('is_duplicate', $options)) {
  1094. $options['is_duplicate'] = FALSE;
  1095. }
  1096. // if this is a prepared statement check to see if it has already been prepared
  1097. $prepared = FALSE;
  1098. if ($options['statement_name']) {
  1099. $prepared = TRUE;
  1100. // we need to get a persistent connection. If one exists this function
  1101. // will not recreate it, but if not it will create one and store it in
  1102. // a Drupal variable for reuse later.
  1103. $connection = tripal_db_persistent_chado();
  1104. // if we cannot get a connection the abandon the prepared statement
  1105. if (!$connection) {
  1106. $prepared = FALSE;
  1107. unset($options['statement_name']);
  1108. }
  1109. }
  1110. else {
  1111. //print "NO STATEMENT (select): $table\n";
  1112. //debug_print_backtrace();
  1113. }
  1114. // check that our columns and values arguments are proper arrays
  1115. if (!is_array($columns)) {
  1116. watchdog('tripal_core', 'the $columns argument for tripal_core_chado_select must be an array.');
  1117. return FALSE;
  1118. }
  1119. if (!is_array($values)) {
  1120. watchdog('tripal_core', 'the $values argument for tripal_core_chado_select must be an array.');
  1121. return FALSE;
  1122. }
  1123. // get the table description
  1124. $table_desc = tripal_core_get_chado_table_schema($table);
  1125. $select = '';
  1126. $from = '';
  1127. $where = '';
  1128. $args = array();
  1129. // if the 'use_unique' option is turned on then we want
  1130. // to remove all but unique keys
  1131. if ($options['is_duplicate'] and array_key_exists('unique keys', $table_desc)) {
  1132. $ukeys = $table_desc['unique keys'];
  1133. $has_results = 0;
  1134. // iterate through the unique constraints and reset the values and columns
  1135. // arrays to only include these fields
  1136. foreach ($ukeys as $cname => $fields) {
  1137. if ($has_results) {
  1138. continue;
  1139. }
  1140. $new_values = array();
  1141. $new_columns = array();
  1142. $new_options = array();
  1143. $uq_sname = "uq_" . $table . "_";
  1144. $has_pkey = 0;
  1145. // include the primary key in the results returned
  1146. if (array_key_exists('primary key', $table_desc)) {
  1147. $has_pkey = 1;
  1148. $pkeys = $table_desc['primary key'];
  1149. foreach ($pkeys as $index => $key) {
  1150. array_push($new_columns, $key);
  1151. }
  1152. }
  1153. // recreate the $values and $columns arrays
  1154. foreach ($fields as $field) {
  1155. if (array_key_exists($field, $values)) {
  1156. $new_values[$field] = $values[$field];
  1157. $uq_sname .= substr($field, 0, 2);
  1158. // if there is no primary key then use the unique contraint fields
  1159. if (!$has_pkey) {
  1160. array_push($new_columns, $field);
  1161. }
  1162. }
  1163. // if the field doesn't exist in the values array then
  1164. // substitute any default values
  1165. elseif (array_key_exists('default', $table_desc['fields'][$field])) {
  1166. $new_values[$field] = $table_desc['fields'][$field]['default'];
  1167. $uq_sname .= substr($field, 0, 2);
  1168. if (!$has_pkey) {
  1169. array_push($new_columns, $field);
  1170. }
  1171. }
  1172. // if there is no value (default or otherwise) check if this field is
  1173. // allowed to be null
  1174. elseif (!$table_desc['fields'][$field]['not null']) {
  1175. $new_values[$field] = NULL;
  1176. $uq_sname .= "n".substr($field, 0, 2);
  1177. if (!$has_pkey) {
  1178. array_push($new_columns, $field);
  1179. }
  1180. }
  1181. // if the array key doesn't exist in the values given by the caller
  1182. // and there is no default value then we cannot check if the record
  1183. // is a duplicate so return FALSE
  1184. else {
  1185. watchdog('tripal_core', "tripal_core_chado_select: There is no value for %field"
  1186. ." thus we cannot check if this record is unique",
  1187. array('%field' => $field), WATCHDOG_ERROR);
  1188. return FALSE;
  1189. }
  1190. }
  1191. $new_options['statement_name'] = $uq_sname;
  1192. $results = tripal_core_chado_select($table, $new_columns, $new_values, $new_options);
  1193. // if we have a duplicate record then return the results
  1194. if (count($results) > 0) {
  1195. $has_results = 1;
  1196. }
  1197. unset($new_columns);
  1198. unset($new_values);
  1199. unset($new_options);
  1200. }
  1201. if ($options['has_record'] and $has_results) {
  1202. return TRUE;
  1203. }
  1204. else {
  1205. return $results;
  1206. }
  1207. }
  1208. foreach ($values as $field => $value) {
  1209. // make sure the field is in the table description. If not then return an error
  1210. // message
  1211. if (!array_key_exists($field, $table_desc['fields'])) {
  1212. watchdog('tripal_core', "tripal_core_chado_select: The field '%field' does not exist ".
  1213. "for the table '%table'. Cannot perform query. Values: %array",
  1214. array('%field' => $field, '%table' => $table, '%array' => print_r($values, 1)), WATCHDOG_ERROR);
  1215. return array();
  1216. }
  1217. $select[] = $field;
  1218. if (is_array($value)) {
  1219. // if the user has specified multiple values for matching then this we
  1220. // want to catch that and save them in our $where array, otherwise
  1221. // we'll descend for a foreign key relationship
  1222. if (array_values($value) === $value) {
  1223. $where[$field] = $value;
  1224. }
  1225. else {
  1226. // select the value from the foreign key relationship for this value
  1227. $foreign_options = array(
  1228. 'regex_columns' => $options['regex_columns'],
  1229. 'case_insensitive_columns' => $options['case_insensitive_columns']
  1230. );
  1231. if (array_key_exists('statement_name', $options) and $options['statement_name']) {
  1232. // add the fk relationship info to the prepared statement name so that
  1233. // we can prepare the selects run by the recrusive tripal_core_chado_get_foreign_key
  1234. // function. we need the statement name to be unique so take the first two characters of each column
  1235. $fk_sname = "fk_" . $table . "_" . $field;
  1236. foreach ($value as $k => $v) {
  1237. $fk_sname .= substr($k, 0, 2);
  1238. }
  1239. $foreign_options['statement_name'] = $fk_sname;
  1240. }
  1241. $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value, $foreign_options);
  1242. if (!$results or count($results)==0) {
  1243. // foreign key records are required
  1244. // thus if none matched then return FALSE and alert the admin through watchdog
  1245. /*watchdog('tripal_core',
  1246. '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',
  1247. array('!table' => $table,
  1248. '!columns' => '<pre>' . print_r($columns, TRUE) . '</pre>',
  1249. '!values' => '<pre>' . print_r($values, TRUE) . '</pre>',
  1250. '!field' => $field,
  1251. ),
  1252. WATCHDOG_WARNING);*/
  1253. return array();
  1254. }
  1255. else {
  1256. $where[$field] = $results;
  1257. }
  1258. }
  1259. }
  1260. else {
  1261. // need to catch a 0 and make int if integer field
  1262. // but we don't want to catch a NULL
  1263. if ($value === NULL) {
  1264. $where[$field] = NULL;
  1265. }
  1266. elseif ($table_desc['fields'][$field]['type'] == 'int') {
  1267. $where[$field][] = (int) $value;
  1268. }
  1269. else {
  1270. $where[$field][] = $value;
  1271. }
  1272. }
  1273. }
  1274. // now build the SQL and prepared SQL statements. We may not use
  1275. // the prepared statement if it wasn't requested in the options of if the
  1276. // argument in a where statement has multiple values.
  1277. if (empty($where)) {
  1278. // sometimes want to select everything
  1279. $sql = "SELECT " . implode(', ', $columns) . " ";
  1280. $sql .= "FROM {$table} ";
  1281. // we don't prepare a statement if there is no where clause
  1282. $prepared = FALSE;
  1283. }
  1284. else {
  1285. $sql = "SELECT " . implode(', ', $columns) . " ";
  1286. $sql .= "FROM {$table} ";
  1287. $sql .= "WHERE ";
  1288. $psql = $sql; // prepared SQL statement;
  1289. $i = 1;
  1290. $pvalues = array();
  1291. $itypes = array();
  1292. foreach ($where as $field => $value) {
  1293. // if we have multiple values returned then we need an 'IN' statement
  1294. // in our where statement
  1295. if (count($value) > 1) {
  1296. $sql .= "$field IN (" . db_placeholders($value, 'varchar') . ") AND ";
  1297. foreach ($value as $v) {
  1298. $args[] = $v;
  1299. // we can't do a prepared statement with an 'IN' statement in a
  1300. // where clause because we can't guarantee we'll always have the
  1301. // same number of elements.
  1302. $prepared = FALSE;
  1303. }
  1304. }
  1305. // if we have a null value then we need an IS NULL in our where statement
  1306. elseif ($value === NULL) {
  1307. $sql .= "$field IS NULL AND ";
  1308. $psql .= "$field IS NULL AND ";
  1309. // Need to remove one from the argument count b/c nulls don't add an argument
  1310. $i--;
  1311. }
  1312. // if we have a single value then we need an = in our where statement
  1313. else {
  1314. $operator = '=';
  1315. if (in_array($field, $options['regex_columns'])) {
  1316. $operator = '~*';
  1317. }
  1318. // get the types for the prepared statement. First check if the type
  1319. // is an integer
  1320. if (strcasecmp($table_desc['fields'][$field]['type'], 'serial')==0 OR
  1321. strcasecmp($table_desc['fields'][$field]['type'], 'int')==0 OR
  1322. strcasecmp($table_desc['fields'][$field]['type'], 'integer')==0) {
  1323. $sql .= "$field $operator %d AND ";
  1324. $psql .= "$field $operator \$" . $i . " AND ";
  1325. $args[] = $value[0];
  1326. // set the variables needed for the prepared statement
  1327. $idatatypes[] = 'int';
  1328. $itypes[] = '%d';
  1329. $pvalues[] = $value[0];
  1330. }
  1331. elseif (strcasecmp($table_desc['fields'][$field]['type'], 'boolean')==0) {
  1332. $sql .= "$field $operator %s AND ";
  1333. $psql .= "$field $operator \$" . $i . " AND ";
  1334. $args[] = $value[0];
  1335. // set the variables needed for the prepared statement
  1336. $idatatypes[] = 'bool';
  1337. $itypes[] = '%d';
  1338. $pvalues[] = $value[0];
  1339. }
  1340. elseif (strcasecmp($table_desc['fields'][$field]['type'], 'float')==0) {
  1341. $sql .= "$field $operator %s AND ";
  1342. $psql .= "$field $operator \$" . $i . " AND ";
  1343. $args[] = $value[0];
  1344. // set the variables needed for the prepared statement
  1345. $idatatypes[] = 'numeric';
  1346. $itypes[] = '%f';
  1347. $pvalues[] = $value[0];
  1348. }
  1349. // else the type is a text
  1350. else {
  1351. if (in_array($field, $options['case_insensitive_columns'])) {
  1352. $sql .= "lower($field) $operator lower('%s') AND ";
  1353. $psql .= "lower($field) $operator lower('\$" . $i . "') AND ";
  1354. $args[] = $value;
  1355. }
  1356. else {
  1357. $sql .= "$field $operator '%s' AND ";
  1358. $psql .= "$field $operator \$" . $i . " AND ";
  1359. $args[] = $value[0];
  1360. }
  1361. // set the variables needed for the prepared statement
  1362. $idatatypes[] = 'text';
  1363. $itypes[] = "'%s'";
  1364. $pvalues[] = $value[0];
  1365. }
  1366. }
  1367. $i++;
  1368. } // end foreach item in where clause
  1369. $sql = drupal_substr($sql, 0, -4); // get rid of the trailing 'AND '
  1370. $psql = drupal_substr($psql, 0, -4); // get rid of the trailing 'AND '
  1371. } // end if(empty($where)){ } else {
  1372. // finally add any ordering of the results to the SQL statement
  1373. if (count($options['order_by']) > 0) {
  1374. $sql .= " ORDER BY ";
  1375. $psql .= " ORDER BY ";
  1376. foreach ($options['order_by'] as $field => $dir) {
  1377. $sql .= "$field $dir, ";
  1378. $psql .= "$field $dir, ";
  1379. }
  1380. $sql = drupal_substr($sql, 0, -2); // get rid of the trailing ', '
  1381. $psql = drupal_substr($psql, 0, -2); // get rid of the trailing ', '
  1382. }
  1383. // finish constructing the prepared SQL statement
  1384. if ($options['statement_name']) {
  1385. $psql = "PREPARE " . $options['statement_name'] . " (" . implode(', ', $idatatypes) . ") AS " . $psql;
  1386. }
  1387. // if the caller has requested the SQL rather than the results...
  1388. // which happens in the case of wanting to use the Drupal pager, then do so
  1389. if ($options['return_sql'] == TRUE) {
  1390. return array('sql' => $sql, 'args' => $args);
  1391. }
  1392. // prepare the statement
  1393. if ($prepared) {
  1394. // if this is the first time we've run this query
  1395. // then we need to do the prepare, otherwise just execute
  1396. if ($options['is_prepared'] != TRUE) {
  1397. $status = tripal_core_chado_prepare($options['statement_name'], $psql, $idatatypes);
  1398. if (!$status) {
  1399. return FALSE;
  1400. }
  1401. }
  1402. $sql = "EXECUTE " . $options['statement_name'] . "(" . implode(", ", $itypes) . ")";
  1403. // WARNING: This call creates a memory leak: if you remove the $pvalues it doesn't
  1404. // do this. Got to find out what's causing this.
  1405. $resource = tripal_core_chado_execute_prepared($options['statement_name'], $sql, $pvalues);
  1406. }
  1407. else {
  1408. $resource = chado_query($sql, $args);
  1409. }
  1410. // format results into an array
  1411. $results = array();
  1412. while ($r = db_fetch_object($resource)) {
  1413. $results[] = $r;
  1414. }
  1415. if ($options['has_record']) {
  1416. return count($results);
  1417. }
  1418. return $results;
  1419. }
  1420. /**
  1421. * Gets the value of a foreign key relationship
  1422. *
  1423. * This function is used by tripal_core_chado_select, tripal_core_chado_insert,
  1424. * and tripal_core_chado_update to iterate through the associate array of
  1425. * values that gets passed to each of those routines. The values array
  1426. * is nested where foreign key contraints are used to specify a value that. See
  1427. * documentation for any of those functions for further information.
  1428. *
  1429. * @param $table_desc
  1430. * A table description for the table with the foreign key relationship to be identified generated by
  1431. * hook_chado_<table name>_schema()
  1432. * @param $field
  1433. * The field in the table that is the foreign key.
  1434. * @param $values
  1435. * An associative array containing the values
  1436. * @param $options
  1437. * An associative array of additional options where the key is the option
  1438. * and the value is the value of that option. These options are passed on to tripal_core_chado_select.
  1439. *
  1440. * Additional Options Include:
  1441. * - case_insensitive_columns
  1442. * An array of columns to do a case insensitive search on.
  1443. * - regex_columns
  1444. * An array of columns where the value passed in should be treated as a regular expression
  1445. *
  1446. * @return
  1447. * A string containg the results of the foreign key lookup, or FALSE if failed.
  1448. *
  1449. * Example usage:
  1450. * @code
  1451. *
  1452. * $values = array(
  1453. * 'genus' => 'Citrus',
  1454. * 'species' => 'sinensis',
  1455. * );
  1456. * $value = tripal_core_chado_get_foreign_key('feature', 'organism_id',$values);
  1457. *
  1458. * @endcode
  1459. * The above code selects a record from the feature table using the three fields
  1460. * that uniquely identify a feature. The $columns array simply lists the columns
  1461. * to select. The $values array is nested such that the organism is identified by
  1462. * way of the organism_id foreign key constraint by specifying the genus and
  1463. * species. The cvterm is also specified using its foreign key and the cv_id
  1464. * for the cvterm is nested as well.
  1465. *
  1466. * @ingroup tripal_chado_api
  1467. */
  1468. function tripal_core_chado_get_foreign_key($table_desc, $field, $values, $options = NULL) {
  1469. // set defaults for options. If we don't set defaults then
  1470. // we get memory leaks when we try to access the elements
  1471. if (!is_array($options)) {
  1472. $options = array();
  1473. }
  1474. if (!array_key_exists('case_insensitive_columns', $options)) {
  1475. $options['case_insensitive_columns'] = array();
  1476. }
  1477. if (!array_key_exists('regex_columns', $options)) {
  1478. $options['regex_columns'] = array();
  1479. }
  1480. // get the list of foreign keys for this table description and
  1481. // iterate through those until we find the one we're looking for
  1482. $fkeys = '';
  1483. if (array_key_exists('foreign keys', $table_desc)) {
  1484. $fkeys = $table_desc['foreign keys'];
  1485. }
  1486. if ($fkeys) {
  1487. foreach ($fkeys as $name => $def) {
  1488. if (is_array($def['table'])) {
  1489. //foreign key was described 2X
  1490. $message = "The foreign key " . $name . " was defined twice. Please check modules "
  1491. ."to determine if hook_chado_schema_<version>_" . $table_desc['table'] . "() was "
  1492. ."implemented and defined this foreign key when it wasn't supposed to. Modules "
  1493. ."this hook was implemented in: " . implode(', ',
  1494. module_implements("chado_" . $table_desc['table'] . "_schema")) . ".";
  1495. watchdog('tripal_core', $message);
  1496. drupal_set_message(check_plain($message), 'error');
  1497. continue;
  1498. }
  1499. $table = $def['table'];
  1500. $columns = $def['columns'];
  1501. // iterate through the columns of the foreign key relationship
  1502. foreach ($columns as $left => $right) {
  1503. // does the left column in the relationship match our field?
  1504. if (strcmp($field, $left) == 0) {
  1505. // the column name of the foreign key matches the field we want
  1506. // so this is the right relationship. Now we want to select
  1507. $select_cols = array($right);
  1508. $result = tripal_core_chado_select($table, $select_cols, $values, $options);
  1509. $fields = array();
  1510. if ($result and count($result) > 0) {
  1511. foreach ($result as $obj) {
  1512. $fields[] = $obj->$right;
  1513. }
  1514. return $fields;
  1515. }
  1516. }
  1517. }
  1518. }
  1519. }
  1520. else {
  1521. // TODO: what do we do if we get to this point and we have a fk
  1522. // relationship expected but we don't have any definition for one in the
  1523. // table schema??
  1524. $version = tripal_core_get_chado_version(TRUE);
  1525. $message = t("There is no foreign key relationship defined for " . $field . ".
  1526. To define a foreign key relationship, determine the table this foreign
  1527. key referrs to (<foreign table>) and then implement
  1528. hook_chado_chado_schema_v<version>_<foreign table>(). See
  1529. tripal_feature_chado_v1_2_schema_feature for an example. Chado version: $version");
  1530. watchdog('tripal_core', $message);
  1531. drupal_set_message(check_plain($message), 'error');
  1532. }
  1533. return array();
  1534. }
  1535. /**
  1536. * Generates an object containing the full details of a record(s) in chado.
  1537. *
  1538. * This differs from the objects returned by tripal_core_chado_select in so far as all foreign key
  1539. * relationships have been followed meaning you have more complete details. Thus this function
  1540. * should be used whenever you need a full variable and tripal_core_chado_select should be used if
  1541. * you only case about a few columns.
  1542. *
  1543. * @param $table
  1544. * The name of the base table to generate a variable for
  1545. * @param $values
  1546. * A select values array that selects the records you want from the base table
  1547. * (this has the same form as tripal_core_chado_select)
  1548. * @param $base_options
  1549. * An array containing options for the base table. For example, an
  1550. * option of 'order_by' may be used to sort results in the base table
  1551. * if more than one are returned. The options must be compatible with
  1552. * the options accepted by the tripal_core_chado_select() function.
  1553. * Additionally, These options are available for this function:
  1554. * -return_array:
  1555. * can be provided to force the function to always return an array. Default
  1556. * behavior is to return a single record if only one record exists or to return
  1557. * an array if multiple records exist.
  1558. * - include_fk:
  1559. * an array of FK relationships to fallow. By default, the
  1560. * tripal_core_chado_select function will follow all FK relationships but this
  1561. * may generate more queries then is desired. Provide an array specifying the
  1562. * fields to include. For example, if including the cvterm, cv and dbxref records
  1563. * for a property the following array would work:
  1564. * array('type_id' => array('cv_id' => 1, 'dbxref_id' => 1)).
  1565. * Typicall, to expadn a property, this function would also include the db record
  1566. * through the db_id foreign key with the dbxref and db tables, but becuase
  1567. * it is not included in the array it will not be included in the results.
  1568. * @return
  1569. * Either an object (if only one record was selected from the base table)
  1570. * or an array of objects (if more than one record was selected from the base table).
  1571. * If the option 'return_array' is provided the function always returns an array.
  1572. *
  1573. * Example Usage:
  1574. * @code
  1575. $values = array(
  1576. 'name' => 'Medtr4g030710'
  1577. );
  1578. $features = tripal_core_generate_chado_var('feature', $values);
  1579. * @endcode
  1580. * This will return an object if there is only one feature with the name Medtr4g030710 or it will
  1581. * return an array of feature objects if more than one feature has that name.
  1582. *
  1583. * Note to Module Designers: Fields can be excluded by default from these objects by implementing
  1584. * one of the following hooks:
  1585. * - hook_exclude_field_from_tablename_by_default (where tablename is the name of the table):
  1586. * This hook allows you to add fields to be excluded on a per table basis. Simply implement
  1587. * this hook to return an array of fields to be excluded. For example:
  1588. * @code
  1589. mymodule_exclude_field_from_feature_by_default() {
  1590. return array('residues' => TRUE);
  1591. }
  1592. * @endcode
  1593. * will ensure that feature.residues is ecluded from a feature object by default.
  1594. * - hook_exclude_type_by_default:
  1595. * This hook allows you to exclude fields from all tables that are of a given postgresql field
  1596. * type. Simply implement this hook to return an array of postgresql types mapped to criteria.
  1597. * Then all fields of that type where the criteria supplied returns TRUE will be excluded from
  1598. * any table. Tokens available in criteria are &gt;field_value&lt; and &gt;field_name&lt; . For example:
  1599. * @code
  1600. mymodule_exclude_type_by_default() {
  1601. return array('text' => 'length(&gt;field_value&lt; ) > 50');
  1602. }
  1603. * @endcode
  1604. * 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.
  1605. *
  1606. * @ingroup tripal_chado_api
  1607. */
  1608. function tripal_core_generate_chado_var($table, $values, $base_options = array()) {
  1609. $all = new stdClass();
  1610. $return_array = 0;
  1611. if (array_key_exists('return_array', $base_options)) {
  1612. $return_array = 1;
  1613. }
  1614. $include_fk = 0;
  1615. if (array_key_exists('include_fk', $base_options)) {
  1616. $include_fk = $base_options['include_fk'];
  1617. }
  1618. // get description for the current table----------------------------------------------------------
  1619. $table_desc = tripal_core_get_chado_table_schema($table);
  1620. if (!$table_desc or count($table_desc) == 0) {
  1621. watchdog('tripal_core', "tripal_core_generate_chado_var: The table '%table' has not been defined. ".
  1622. "and cannot be expanded. If this is a custom table, please add it using the Tripal ".
  1623. "custom table interface.", array('%table' => $table), WATCHDOG_ERROR);
  1624. if ($return_array) {
  1625. return array();
  1626. }
  1627. return FALSE;
  1628. }
  1629. $table_primary_key = $table_desc['primary key'][0];
  1630. $table_columns = array_keys($table_desc['fields']);
  1631. // Expandable fields without value needed for criteria--------------------------------------------
  1632. $all->expandable_fields = array();
  1633. if ($table_desc['referring_tables']) {
  1634. $all->expandable_tables = $table_desc['referring_tables'];
  1635. }
  1636. else {
  1637. $all->expandable_tables = array();
  1638. }
  1639. $all->expandable_nodes = array();
  1640. // Get fields to be removed by name.................................
  1641. $fields_to_remove = module_invoke_all('exclude_field_from_' . $table . '_by_default');
  1642. foreach ($fields_to_remove as $field_name => $criteria) {
  1643. //replace &gt;field_name&lt; with the current field name &
  1644. $criteria = preg_replace('/&gt;field_name&lt; /', addslashes($field_name), $criteria);
  1645. // if field_value needed we can't deal with this field yet
  1646. if (preg_match('/&gt;field_value&lt; /', $criteria)) {
  1647. break;
  1648. }
  1649. //if criteria then remove from query
  1650. // @coder-ignore: only module designers can populate $criteria -not security risk
  1651. $success = drupal_eval('<?php return ' . $criteria . '; ?>');
  1652. // watchdog('tripal_core',
  1653. // 'Evaluating criteria (%criteria) for field %field in tripal_core_generate_chado_var for %table evaluated to %success',
  1654. // array('%table' => $table, '%criteria'=>$criteria, '%field' => $field_name, '%success'=>$success),
  1655. // WATCHDOG_NOTICE
  1656. // );
  1657. if ($success) {
  1658. unset($table_columns[array_search($field_name, $table_columns)]);
  1659. unset($fields_to_remove[$field_name]);
  1660. $all->expandable_fields[] = $table . '.' . $field_name;
  1661. }
  1662. }
  1663. //Get fields to be removed by type................................
  1664. $types_to_remove = module_invoke_all('exclude_type_by_default');
  1665. $field_types = array();
  1666. foreach ($table_desc['fields'] as $field_name => $field_array) {
  1667. $field_types[$field_array['type']][] = $field_name;
  1668. }
  1669. foreach ($types_to_remove as $field_type => $criteria) {
  1670. // if there are fields of that type to remove
  1671. if (is_array($field_types[$field_type])) {
  1672. //replace &gt;field_name&lt; with the current field name &
  1673. $criteria = preg_replace('/&gt;field_name&lt; /', addslashes($field_name), $criteria);
  1674. foreach ($field_types[$field_type] as $field_name) {
  1675. // if field_value needed we can't deal with this field yet
  1676. if (preg_match('/&gt;field_value&lt; /', $criteria)) {
  1677. $fields_to_remove[$field_name] = $criteria;
  1678. continue;
  1679. }
  1680. // if field_value needed we can't deal with this field yet
  1681. if (preg_match('/&gt;field_value&lt; /', $criteria)) {
  1682. break;
  1683. }
  1684. //if criteria then remove from query
  1685. // @coder-ignore: only module designers can populate $criteria -not security risk
  1686. $success = drupal_eval('<?php return ' . $criteria . '; ?>');
  1687. // watchdog('tripal_core',
  1688. // 'Evaluating criteria (%criteria) for field %field of $type in tripal_core_generate_chado_var for %table evaluated to %success',
  1689. // array('%table'=>$table, '%criteria'=>$criteria, '%field'=>$field_name, '%type'=>$field_type, '%success'=>$success),
  1690. // WATCHDOG_NOTICE
  1691. // );
  1692. if ($success) {
  1693. unset($table_columns[array_search($field_name, $table_columns)]);
  1694. $all->expandable_fields[] = $table . '.' . $field_name;
  1695. }
  1696. } //end of foreach field of that type
  1697. }
  1698. } //end of foreach type to be removed
  1699. // get the values for the record in the current table---------------------------------------------
  1700. $results = tripal_core_chado_select($table, $table_columns, $values, $base_options);
  1701. if ($results) {
  1702. foreach ($results as $key => $object) {
  1703. // Add empty expandable_x arrays
  1704. $object->expandable_fields = $all->expandable_fields;
  1705. $object->expandable_tables = $all->expandable_tables;
  1706. $object->expandable_nodes = $all->expandable_nodes;
  1707. // add curent table
  1708. $object->tablename = $table;
  1709. // check if the current table maps to a node type-----------------------------------------------
  1710. // if this table is connected to a node there will be a chado_tablename table in drupal
  1711. if (db_table_exists('chado_' . $table)) {
  1712. // that has a foreign key to this one ($table_desc['primary key'][0]
  1713. // and to the node table (nid)
  1714. $sql = "SELECT %s, nid FROM {chado_%s} WHERE %s=%d";
  1715. $mapping = db_fetch_object(db_query($sql, $table_primary_key, $table,
  1716. $table_primary_key, $object->{$table_primary_key}));
  1717. if ($mapping->{$table_primary_key}) {
  1718. $object->nid = $mapping->nid;
  1719. $object->expandable_nodes[] = $table;
  1720. }
  1721. }
  1722. // remove any fields where criteria need to be evalulated---------------------------------------
  1723. foreach ($fields_to_remove as $field_name => $criteria) {
  1724. if (!isset($object->{$field_name})) {
  1725. break;
  1726. }
  1727. $criteria = preg_replace('/&gt;field_value&lt; /', addslashes($object->{$field_name}), $criteria);
  1728. //if criteria then remove from query
  1729. // @coder-ignore: only module designers can populate $criteria -not security risk
  1730. $success = drupal_eval('<?php return ' . $criteria . '; ?>');
  1731. // watchdog('tripal_core',
  1732. // 'Evaluating criteria (%criteria) for field %field in tripal_core_generate_chado_var for %table evaluated to %success',
  1733. // array('%table' => $table, '%criteria'=>$criteria, '%field' => $field_name, '%success'=>$success),
  1734. // WATCHDOG_NOTICE
  1735. // );
  1736. if ($success) {
  1737. unset($object->{$field_name});
  1738. $object->expandable_fields[] = $table . '.' . $field_name;
  1739. }
  1740. }
  1741. // recursively follow foreign key relationships nesting objects as we go------------------------
  1742. if ($table_desc['foreign keys']) {
  1743. foreach ($table_desc['foreign keys'] as $foreign_key_array) {
  1744. $foreign_table = $foreign_key_array['table'];
  1745. foreach ($foreign_key_array['columns'] as $foreign_key => $primary_key) {
  1746. // Note: Foreign key is the field in the current table whereas primary_key is the field in
  1747. // the table referenced by the foreign key
  1748. //Dont do anything if the foreign key is empty
  1749. if (empty($object->{$foreign_key})) {
  1750. continue;
  1751. }
  1752. if ($include_fk) {
  1753. // don't recurse if the callee has supplied an $fk_include list and this
  1754. // FK table is not in the list.
  1755. if (is_array($include_fk) and !array_key_exists($foreign_key, $include_fk)) {
  1756. continue;
  1757. }
  1758. // if we have the option but it is not an array then we don't recurse any furutehr
  1759. if (!is_array($include_fk)) {
  1760. continue;
  1761. }
  1762. }
  1763. // get the record from the foreign table
  1764. $foreign_values = array($primary_key => $object->{$foreign_key});
  1765. $options = array();
  1766. if (is_array($include_fk)) {
  1767. $options['include_fk'] = $include_fk[$foreign_key];
  1768. }
  1769. $foreign_object = tripal_core_generate_chado_var($foreign_table, $foreign_values, $options);
  1770. // add the foreign record to the current object in a nested manner
  1771. $object->{$foreign_key} = $foreign_object;
  1772. // Flatten expandable_x arrays so only in the bottom object
  1773. if (is_array($object->{$foreign_key}->expandable_fields)) {
  1774. $object->expandable_fields = array_merge(
  1775. $object->expandable_fields,
  1776. $object->{$foreign_key}->expandable_fields
  1777. );
  1778. unset($object->{$foreign_key}->expandable_fields);
  1779. }
  1780. if (is_array($object->{$foreign_key}->expandable_tables)) {
  1781. $object->expandable_tables = array_merge(
  1782. $object->expandable_tables,
  1783. $object->{$foreign_key}->expandable_tables
  1784. );
  1785. unset($object->{$foreign_key}->expandable_tables);
  1786. }
  1787. if (is_array($object->{$foreign_key}->expandable_nodes)) {
  1788. $object->expandable_nodes = array_merge(
  1789. $object->expandable_nodes,
  1790. $object->{$foreign_key}->expandable_nodes
  1791. );
  1792. unset($object->{$foreign_key}->expandable_nodes);
  1793. }
  1794. }
  1795. }
  1796. $results[$key] = $object;
  1797. }
  1798. }
  1799. }
  1800. // check only one result returned
  1801. if (!$return_array) {
  1802. if (sizeof($results) == 1) {
  1803. // add results to object
  1804. return $results[0];
  1805. }
  1806. elseif (!empty($results)) {
  1807. return $results;
  1808. }
  1809. else {
  1810. // no results returned
  1811. }
  1812. }
  1813. // the caller has requested results are always returned as
  1814. // an array
  1815. else {
  1816. if (!$results) {
  1817. return array();
  1818. }
  1819. else {
  1820. return $results;
  1821. }
  1822. }
  1823. }
  1824. /**
  1825. * Retrieves fields/tables/nodes that were excluded by default from a variable and adds them
  1826. *
  1827. * This function exists to allow tripal_core_generate_chado_var() to excldue some
  1828. * fields/tables/nodes from the default form of a variable without making it extremely difficult for
  1829. * the tripal admin to get at these variables if he/she wants them.
  1830. *
  1831. * @param $object
  1832. * This must be an object generated using tripal_core_generate_chado_var()
  1833. * @param $type
  1834. * Must be one of 'field', 'table', 'node'. Indicates what is being expanded.
  1835. * @param $to_expand
  1836. * The name of the field/table/node to be expanded
  1837. * @param $table_options
  1838. * An array containing options for the base table. For example, an
  1839. * option of 'order_by' may be used to sort results in the base table
  1840. * if more than one are returned. The options must be compatible with
  1841. * the options accepted by the tripal_core_chado_select() function.
  1842. * Additionally, The option 'return_array' can be provided to force
  1843. * the function to expand tables as an array. Default behavior is to expand
  1844. * a table as single record if only one record exists or to expand as an array if
  1845. * multiple records exist.
  1846. * @return
  1847. * A chado object supplemented with the field/table/node requested to be expanded.
  1848. * If the type is a table and it has already been expanded no changes is made to the
  1849. * returned object
  1850. *
  1851. * Example Usage:
  1852. * @code
  1853. // Get a chado object to be expanded
  1854. $values = array(
  1855. 'name' => 'Medtr4g030710'
  1856. );
  1857. $features = tripal_core_generate_chado_var('feature', $values);
  1858. // Expand the organism node
  1859. $feature = tripal_core_expand_chado_vars($feature, 'node', 'organism');
  1860. // Expand the feature.residues field
  1861. $feature = tripal_core_expand_chado_vars($feature, 'field', 'feature.residues');
  1862. // Expand the feature properties (featureprop table)
  1863. $feature = tripal_core_expand_chado_vars($feature, 'table', 'featureprop');
  1864. * @endcode
  1865. *
  1866. * @ingroup tripal_chado_api
  1867. */
  1868. function tripal_core_expand_chado_vars($object, $type, $to_expand, $table_options = array()) {
  1869. $base_table = $object->tablename;
  1870. // check to see if we are expanding an array of objects
  1871. if (is_array($object)) {
  1872. foreach ($object as $index => $o) {
  1873. $object[$index] = tripal_core_expand_chado_vars($o, $type, $to_expand);
  1874. }
  1875. return $object;
  1876. }
  1877. switch ($type) {
  1878. case "field": //--------------------------------------------------------------------------------
  1879. if (preg_match('/(\w+)\.(\w+)/', $to_expand, $matches)) {
  1880. $tablename = $matches[1];
  1881. $fieldname = $matches[2];
  1882. $table_desc = tripal_core_get_chado_table_schema($tablename);
  1883. $values = array();
  1884. foreach ($table_desc['primary key'] as $key) {
  1885. $values[$key] = $object->{$key};
  1886. }
  1887. if ($base_table == $tablename) {
  1888. //get the field
  1889. $results = tripal_core_chado_select($tablename, array($fieldname), $values);
  1890. $object->{$fieldname} = $results[0]->{$fieldname};
  1891. $object->expanded = $to_expand;
  1892. }
  1893. else {
  1894. //We need to recurse -the field is in a nested object
  1895. foreach ((array) $object as $field_name => $field_value) {
  1896. if (is_object($field_value)) {
  1897. $object->{$field_name} = tripal_core_expand_chado_vars(
  1898. $field_value,
  1899. 'field',
  1900. $to_expand
  1901. );
  1902. }
  1903. } //end of for each field in the current object
  1904. }
  1905. }
  1906. else {
  1907. watchdog('tripal_core', 'tripal_core_expand_chado_vars: Field (%field) not in the right format. ".
  1908. "It should be <tablename>.<fieldname>', WATCHDOG_ERROR);
  1909. }
  1910. break;
  1911. case "table": //--------------------------------------------------------------------------------
  1912. $foreign_table = $to_expand;
  1913. // don't expand the table it already is expanded
  1914. if (array_key_exists($foreign_table, $object)) {
  1915. return $object;
  1916. }
  1917. $foreign_table_desc = tripal_core_get_chado_table_schema($foreign_table);
  1918. // If it's connected to the base table
  1919. if ($foreign_table_desc['foreign keys'][$base_table]) {
  1920. foreach ($foreign_table_desc['foreign keys'][$base_table]['columns'] as $left => $right) {
  1921. if (!$object->{$right}) {
  1922. continue;
  1923. }
  1924. if (is_array($values)) {
  1925. $values = array_merge($values, array($left => $object->{$right}) );
  1926. }
  1927. else {
  1928. $values = array($left => $object->{$right});
  1929. }
  1930. // if a prepared statement is provide then generate a new name
  1931. $new_options = $table_options;
  1932. if (array_key_exists('statement_name', $table_options)) {
  1933. $new_options['statement_name'] = "exp_" . $foreign_table . "_" . substr($left, 0, 2) . substr($right, 0, 2);
  1934. }
  1935. $foreign_object = tripal_core_generate_chado_var($foreign_table, array($left => $object->{$right}), $new_options);
  1936. if ($foreign_object) {
  1937. // in the case where the foreign key relationships exists more
  1938. // than once with the same table we want to alter the
  1939. // array structure
  1940. if (count($foreign_table_desc['foreign keys'][$base_table]['columns']) > 1) {
  1941. if (!is_object($object->{$foreign_table})) {
  1942. $object->{$foreign_table} = new stdClass();
  1943. }
  1944. $object->{$foreign_table}->{$left} = $foreign_object;
  1945. $object->expanded = $to_expand;
  1946. }
  1947. else {
  1948. $object->{$foreign_table} = $foreign_object;
  1949. $object->expanded = $to_expand;
  1950. }
  1951. }
  1952. // if the object returned is NULL then handle that
  1953. else {
  1954. if (count($foreign_table_desc['foreign keys'][$base_table]['columns']) > 1) {
  1955. $object->{$foreign_table}->{$left} = NULL;
  1956. }
  1957. else {
  1958. $object->{$foreign_table} = NULL;
  1959. }
  1960. }
  1961. }
  1962. }
  1963. else {
  1964. // We need to recurse -the table has a relationship to one of the nested objects
  1965. $did_expansion = 0;
  1966. foreach ((array) $object as $field_name => $field_value) {
  1967. // if we have a nested object ->expand the table in it
  1968. if (is_object($field_value)) {
  1969. $did_expansion = 1;
  1970. $object->{$field_name} = tripal_core_expand_chado_vars($field_value, 'table', $foreign_table);
  1971. }
  1972. }
  1973. // if we did not expand this table we should return a message that the foreign table
  1974. // could not be expanded
  1975. if (!$did_expansion) {
  1976. watchdog('tripal_core', 'tripal_core_expand_chado_vars: Could not expand table, %table. It is ',
  1977. 'not in a foreign key relationship with the base object nor with any other expanded table. ' .
  1978. 'Check the table definition to ensure that a proper foreign key relationship is present.',
  1979. array('%table' => $foreign_table), WATCHDOG_ERROR);
  1980. }
  1981. }
  1982. break;
  1983. case "node": //---------------------------------------------------------------------------------
  1984. //if the node to be expanded is for our base table, then just expand it
  1985. if ($object->tablename == $to_expand) {
  1986. $node = node_load($object->nid);
  1987. if ($node) {
  1988. $object->expanded = $to_expand;
  1989. $node->expandable_fields = $object->expandable_fields;
  1990. unset($object->expandable_fields);
  1991. $node->expandable_tables = $object->expandable_tables;
  1992. unset($object->expandable_tables);
  1993. $node->expandable_nodes = $object->expandable_nodes;
  1994. unset($object->expandable_nodes);
  1995. $node->{$base_table} = $object;
  1996. $object = $node;
  1997. }
  1998. else {
  1999. watchdog('tripal_core', 'tripal_core_expand_chado_vars: No node matches the nid (%nid) supplied.',
  2000. array('%nid' => $object->nid), WATCHDOG_ERROR);
  2001. } //end of if node
  2002. }
  2003. else {
  2004. //We need to recurse -the node to expand is one of the nested objects
  2005. foreach ((array) $object as $field_name => $field_value) {
  2006. if (is_object($field_value)) {
  2007. $object->{$field_name} = tripal_core_expand_chado_vars(
  2008. $field_value,
  2009. 'node',
  2010. $to_expand
  2011. );
  2012. }
  2013. } //end of for each field in the current object
  2014. }
  2015. break;
  2016. default:
  2017. watchdog('tripal_core', 'tripal_core_expand_chado_vars: Unrecognized type (%type). Should be one of "field", "table", "node".',
  2018. array('%type' => $type), WATCHDOG_ERROR);
  2019. return FALSE;
  2020. }
  2021. //move extended array downwards-------------------------------------------------------------------
  2022. if (!$object->expanded) {
  2023. //if there's no extended field then go hunting for it
  2024. foreach ( (array)$object as $field_name => $field_value) {
  2025. if (is_object($field_value)) {
  2026. if (isset($field_value->expanded)) {
  2027. $object->expanded = $field_value->expanded;
  2028. unset($field_value->expanded);
  2029. }
  2030. }
  2031. }
  2032. }
  2033. //try again becasue now we might have moved it down
  2034. if ($object->expanded) {
  2035. $expandable_name = 'expandable_' . $type . 's';
  2036. if ($object->{$expandable_name}) {
  2037. $key_to_remove = array_search($object->expanded, $object->{$expandable_name});
  2038. unset($object->{$expandable_name}[$key_to_remove]);
  2039. unset($object->expanded);
  2040. }
  2041. else {
  2042. // if there is an expandable array then we've reached the base object
  2043. // if we get here and don't have anything expanded then something went wrong
  2044. // watchdog(
  2045. // 'tripal_core',
  2046. // 'tripal_core_expand_chado_vars: Unable to expand the %type %to_expand',
  2047. // array('%type'=>$type, '%to_expand'=>$to_expand),
  2048. // WATCHDOG_ERROR
  2049. // );
  2050. } //end of it we've reached the base object
  2051. }
  2052. return $object;
  2053. }
  2054. /**
  2055. * Implements hook_exclude_type_by_default()
  2056. *
  2057. * This hooks allows fields of a specified type that match a specified criteria to be excluded by
  2058. * default from any table when tripal_core_generate_chado_var() is called. Keep in mind that if
  2059. * fields are excluded by default they can always be expanded at a later date using
  2060. * tripal_core_expand_chado_vars().
  2061. *
  2062. * Criteria are php strings that evaluate to either TRUE or FALSE. These strings are evaluated using
  2063. * drupal_eval() which suppresses syntax errors and throws watchdog entries of type php. There are
  2064. * also watchdog entries of type tripal_core stating the exact criteria evaluated. Criteria can
  2065. * contain the following tokens:
  2066. * - &gt;field_name&lt;
  2067. * Replaced by the name of the field to be excluded
  2068. * - &gt;field_value&lt;
  2069. * Replaced by the value of the field in the current record
  2070. * Also keep in mind that if your criteria doesn't contain the &gt;field_value&lt; token then it will be
  2071. * evaluated before the query is executed and if the field is excluded it won't be included in the
  2072. * query.
  2073. *
  2074. * @return
  2075. * An array of type => criteria where the type is excluded if the criteria evaluates to TRUE
  2076. *
  2077. * @ingroup tripal_chado_api
  2078. */
  2079. function tripal_core_exclude_type_by_default() {
  2080. return array('text' => 'strlen("&gt;field_value&lt; ") > 100');
  2081. }
  2082. /**
  2083. * Implements hook_exclude_field_from_<tablename>_by_default()
  2084. *
  2085. * This hooks allows fields from a specified table that match a specified criteria to be excluded by
  2086. * default from any table when tripal_core_generate_chado_var() is called. Keep in mind that if
  2087. * fields are excluded by default they can always be expanded at a later date using
  2088. * tripal_core_expand_chado_vars().
  2089. *
  2090. * Criteria are php strings that evaluate to either TRUE or FALSE. These strings are evaluated using
  2091. * drupal_eval() which suppresses syntax errors and throws watchdog entries of type php. There are
  2092. * also watchdog entries of type tripal_core stating the exact criteria evaluated. Criteria can
  2093. * contain the following tokens:
  2094. * - &gt;field_name&lt;
  2095. * Replaced by the name of the field to be excluded
  2096. * - &gt;field_value&lt;
  2097. * Replaced by the value of the field in the current record
  2098. * Also keep in mind that if your criteria doesn't contain the &gt;field_value&lt; token then it will be
  2099. * evaluated before the query is executed and if the field is excluded it won't be included in the
  2100. * query.
  2101. *
  2102. * @return
  2103. * An array of type => criteria where the type is excluded if the criteria evaluates to TRUE
  2104. *
  2105. * @ingroup tripal_chado_api
  2106. */
  2107. function tripal_core_exclude_field_from_feature_by_default() {
  2108. return array();
  2109. }
  2110. /**
  2111. * Use this function instead of db_query() to avoid switching databases
  2112. * when making query to the chado database
  2113. *
  2114. * Will use a chado persistent connection if it already exists
  2115. *
  2116. * @param $sql
  2117. * The sql statement to execute
  2118. *
  2119. * @returns
  2120. * A database query result resource or FALSE if the query was not
  2121. * executed correctly
  2122. */
  2123. function chado_query($sql) {
  2124. global $persistent_chado;
  2125. $is_local = tripal_core_is_chado_local();
  2126. $args = func_get_args();
  2127. array_shift($args); // remove the $sql from the argument list
  2128. $sql = db_prefix_tables($sql);
  2129. if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
  2130. $args = $args[0];
  2131. }
  2132. // run the Drupal command to clean up the SQL
  2133. _db_query_callback($args, TRUE);
  2134. $sql = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $sql);
  2135. // add the chado schema to the table names if Chado is local to the Drupal database
  2136. if ($is_local) {
  2137. // TODO: this regular expression really needs to be removed as there are too many
  2138. // cases where it could break. Instead we need to surround tables with brackets
  2139. // like Drupal tables are and then find those and prefix those with chado.
  2140. $sql = preg_replace('/\n/', '', $sql); // remove carriage returns
  2141. // in the statement below we want to add 'chado.' to the beginning of each table
  2142. // we use the FROM keyword to look for tables, but FROM is also used in the
  2143. // 'substring' function of postgres. But since table names can't start with
  2144. // a number we exclude words numeric values. We also exclude tables that
  2145. // already have a schema prefix.
  2146. $sql = preg_replace('/FROM\s+([^0123456789\(][^\.]*?)(\s|$)/i', 'FROM chado.\1 ', $sql);
  2147. $sql = preg_replace('/INNER\s+JOIN\s+([^\.]*?)\s/i', 'INNER JOIN chado.\1 ', $sql);
  2148. }
  2149. //print "$sql\n";
  2150. // Execute the query on the chado database/schema
  2151. // Use the persistent chado connection if it already exists
  2152. if ($persistent_chado) {
  2153. $query = $sql;
  2154. // Duplicate the _db_query code in order to ensure that the drupal
  2155. // $active_db variable is not used in the pg_query command
  2156. // thus changed $active_db to $persistent_chado
  2157. // START COPY FROM _db_query in database.pgsql.inc
  2158. if (variable_get('dev_query', 0)) {
  2159. list($usec, $sec) = explode(' ', microtime());
  2160. $timer = (float) $usec + (float) $sec;
  2161. }
  2162. // if we're local we can just run the query
  2163. if ($is_local) {
  2164. $last_result = pg_query($persistent_chado, $query);
  2165. }
  2166. else {
  2167. $previous_db = tripal_db_set_active('chado');
  2168. $last_result = pg_query($persistent_chado, $query);
  2169. tripal_db_set_active($previous_db);
  2170. }
  2171. if (variable_get('dev_query', 0)) {
  2172. $bt = debug_backtrace();
  2173. $query = $bt[2]['function'] . "\n" . $query;
  2174. list($usec, $sec) = explode(' ', microtime());
  2175. $stop = (float) $usec + (float) $sec;
  2176. $diff = $stop - $timer;
  2177. $queries[] = array($query, $diff);
  2178. }
  2179. if ($last_result !== FALSE) {
  2180. return $last_result;
  2181. }
  2182. else {
  2183. // Indicate to drupal_error_handler that this is a database error.
  2184. ${DB_ERROR} = TRUE;
  2185. trigger_error(check_plain(pg_last_error($persistent_chado) . "\nquery: " . $query), E_USER_WARNING);
  2186. return FALSE;
  2187. }
  2188. // END COPY FROM _db_query in database.pgsql.inc
  2189. }
  2190. else {
  2191. // before running the query we want to prefix the table names with
  2192. // the chado schema. Previously use had to make changes to the
  2193. // search_path but that caused a lot of database calls and wasted
  2194. // resources during long jobs.
  2195. if ($is_local) {
  2196. $results = _db_query($sql);
  2197. }
  2198. else {
  2199. $previous_db = tripal_db_set_active('chado') ;
  2200. $results = _db_query($sql);
  2201. tripal_db_set_active($previous_db);
  2202. }
  2203. }
  2204. return $results;
  2205. }
  2206. /**
  2207. * Get chado id for a node. E.g, if you want to get 'analysis_id' from the
  2208. * 'analysis' table for a synced 'chado_analysis' node, use:
  2209. * $analysis_id = chado_get_id_for_node ('analysis', $node)
  2210. * Likewise,
  2211. * $organism_id = chado_get_id_for_node ('organism', $node)
  2212. * $feature_id = chado_get_id_for_node ('feature', $node)
  2213. */
  2214. function chado_get_id_for_node($table, $node) {
  2215. return db_result(db_query("SELECT %s_id FROM {chado_%s} WHERE nid = %d", $table, $table, $node->nid));
  2216. }
  2217. /**
  2218. * Get node id for a chado feature/organism/analysis. E.g, if you want to
  2219. * get the node id for an analysis, use:
  2220. * $nid = chado_get_node_id ('analysis', $analysis_id)
  2221. * Likewise,
  2222. * $nid = chado_get_node_id ('organism', $organism_id)
  2223. * $nid = chado_get_node_id ('feature', $feature_id)
  2224. */
  2225. function chado_get_node_id($table, $id) {
  2226. return db_result(db_query("SELECT nid FROM {chado_%s} WHERE %s_id = %d", $table, $table, $id));
  2227. }
  2228. /**
  2229. * Retrieve a property for a given base table record
  2230. *
  2231. * @param $basetable
  2232. * The base table for which the property should be retrieved. Thus to retrieve a property
  2233. * for a feature the basetable=feature and property is retrieved from featureprop
  2234. * @param $record_id
  2235. * The foriegn key field of the base table. This should be in integer.
  2236. * @param $property
  2237. * The cvterm name describing the type of properties to be retrieved
  2238. * @param $cv_name
  2239. * The name of the cv that the above cvterm is part of
  2240. *
  2241. * @return
  2242. * An array in the same format as that generated by the function
  2243. * tripal_core_generate_chado_var(). If only one record is returned it
  2244. * is a single object. If more than one record is returned then it is an array
  2245. * of objects
  2246. *
  2247. * @ingroup tripal_chado_api
  2248. */
  2249. function tripal_core_get_property($basetable, $record_id, $property, $cv_name) {
  2250. // get the foreign key for this property table
  2251. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  2252. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  2253. // construct the array of values to be selected
  2254. $values = array(
  2255. $fkcol => $record_id,
  2256. 'type_id' => array(
  2257. 'cv_id' => array(
  2258. 'name' => $cv_name,
  2259. ),
  2260. 'name' => $property,
  2261. 'is_obsolete' => 0
  2262. ),
  2263. );
  2264. $results = tripal_core_generate_chado_var($basetable . 'prop', $values);
  2265. $results = tripal_core_expand_chado_vars($results, 'field', $basetable . 'prop.value');
  2266. return $results;
  2267. }
  2268. /**
  2269. * Insert a property for a given base table. By default if the property already
  2270. * exists a new property is added with the next available rank. If
  2271. * $update_if_present argument is specified then the record will be updated if it
  2272. * exists rather than adding a new property.
  2273. *
  2274. * @param $basetable
  2275. * The base table for which the property should be inserted. Thus to insert a property
  2276. * for a feature the basetable=feature and property is inserted into featureprop
  2277. * @param $record_id
  2278. * The foriegn key field of the base table. This should be in integer.
  2279. * @param $property
  2280. * The cvterm name describing the type of properties to be inserted
  2281. * @param $cv_name
  2282. * The name of the cv that the above cvterm is part of
  2283. * @param $value
  2284. * The value of the property to be inserted (can be empty)
  2285. * @param $update_if_present
  2286. * A boolean indicating whether an existing record should be updated. If the
  2287. * property already exists and this value is not specified or is zero then
  2288. * a new property will be added with the next largest rank.
  2289. *
  2290. * @return
  2291. * Return True on Insert/Update and False otherwise
  2292. *
  2293. * @ingroup tripal_chado_api
  2294. */
  2295. function tripal_core_insert_property($basetable, $record_id, $property,
  2296. $cv_name, $value, $update_if_present = 0) {
  2297. // first see if the property already exists, if the user want's to update
  2298. // then we can do that, but otherwise we want to increment the rank and
  2299. // insert
  2300. $props = tripal_core_get_property($basetable, $record_id, $property, $cv_name);
  2301. if (!is_array($props)) {
  2302. $props = array($props);
  2303. }
  2304. $rank = 0;
  2305. if (count($props) > 0) {
  2306. if ($update_if_present) {
  2307. return tripal_core_update_property($basetable, $record_id, $property, $cv_name, $value);
  2308. }
  2309. else {
  2310. // iterate through the properties returned and check to see if the
  2311. // property with this value already exists if not, get the largest rank
  2312. // and insert the same property but with this new value
  2313. foreach ($props as $p) {
  2314. if ($p->rank > $rank) {
  2315. $rank = $p->rank;
  2316. }
  2317. if (strcmp($p->value, $value) == 0) {
  2318. return TRUE;
  2319. }
  2320. }
  2321. // now add 1 to the rank
  2322. $rank++;
  2323. }
  2324. }
  2325. else {
  2326. watchdog('tripal_core', "Cannot find property '!prop_name'.",
  2327. array('!prop_name' => $property), WATCHDOG_ERROR);
  2328. }
  2329. // get the foreign key for this property table
  2330. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  2331. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  2332. // construct the array of values to be inserted
  2333. $values = array(
  2334. $fkcol => $record_id,
  2335. 'type_id' => array(
  2336. 'cv_id' => array(
  2337. 'name' => $cv_name,
  2338. ),
  2339. 'name' => $property,
  2340. 'is_obsolete' => 0
  2341. ),
  2342. 'value' => $value,
  2343. 'rank' => $rank,
  2344. );
  2345. return tripal_core_chado_insert($basetable . 'prop', $values);
  2346. }
  2347. /**
  2348. * Update a property for a given base table record and property name. This
  2349. * function should be used only if one record of the property will be present.
  2350. * If the property name can have multiple entries (with increasing rank) then
  2351. * use the function named tripal_core_update_property_by_id
  2352. *
  2353. * @param $basetable
  2354. * The base table for which the property should be updated. The property table
  2355. * is constructed using a combination of the base table name and the suffix
  2356. * 'prop' (e.g. basetable = feature then property tabie is featureprop).
  2357. * @param $record_id
  2358. * The foreign key of the basetable to update a property for. This should be in integer.
  2359. * For example, if the basetable is 'feature' then the $record_id should be the feature_id
  2360. * @param $property
  2361. * The cvterm name of property to be updated
  2362. * @param $cv_name
  2363. * The name of the cv that the above cvterm is part of
  2364. * @param $value
  2365. * The value of the property to be inserted (can be empty)
  2366. * @param $insert_if_missing
  2367. * A boolean indicating whether a record should be inserted if one doesn't exist to update
  2368. *
  2369. * Note: The property to be updated is select via the unique combination of $record_id and
  2370. * $property and then it is updated with the supplied value
  2371. *
  2372. * @return
  2373. * Return True on Update/Insert and False otherwise
  2374. *
  2375. * @ingroup tripal_chado_api
  2376. */
  2377. function tripal_core_update_property($basetable, $record_id, $property,
  2378. $cv_name, $value, $insert_if_missing = 0) {
  2379. // first see if the property is missing (we can't update a missing property
  2380. $prop = tripal_core_get_property($basetable, $record_id, $property, $cv_name);
  2381. if (count($prop)==0) {
  2382. if ($insert_if_missing) {
  2383. return tripal_core_insert_property($basetable, $record_id, $property, $cv_name, $value);
  2384. }
  2385. else {
  2386. return FALSE;
  2387. }
  2388. }
  2389. // get the foreign key for this property table
  2390. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  2391. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  2392. // construct the array that will match the exact record to update
  2393. $match = array(
  2394. $fkcol => $record_id,
  2395. 'type_id' => array(
  2396. 'cv_id' => array(
  2397. 'name' => $cv_name,
  2398. ),
  2399. 'name' => $property,
  2400. ),
  2401. );
  2402. // construct the array of values to be updated
  2403. $values = array(
  2404. 'value' => $value,
  2405. );
  2406. return tripal_core_chado_update($basetable . 'prop', $match, $values);
  2407. }
  2408. /**
  2409. * Update a property for a given base table record. This function should be
  2410. * used if multiple records of the same property will be present. Also, use this
  2411. * function to change the property name of an existing property.
  2412. *
  2413. * @param $basetable
  2414. * The base table for which the property should be updated. The property table
  2415. * is constructed using a combination of the base table name and the suffix
  2416. * 'prop' (e.g. basetable = feature then property tabie is featureprop).
  2417. * @param $record_id
  2418. * The primary key of the base table. This should be in integer.
  2419. * For example, if the basetable is 'feature' then the $record_id should be the featureprop_id
  2420. * @param $property
  2421. * The cvterm name of property to be updated
  2422. * @param $cv_name
  2423. * The name of the cv that the above cvterm is part of
  2424. * @param $value
  2425. * The value of the property to be inserted (can be empty)
  2426. *
  2427. * @return
  2428. * Return True on Update/Insert and False otherwise
  2429. *
  2430. * @ingroup tripal_chado_api
  2431. */
  2432. function tripal_core_update_property_by_id($basetable, $record_id, $property,
  2433. $cv_name, $value) {
  2434. // get the primary key for this property table
  2435. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  2436. $pkcol = $table_desc['primary key'][0];
  2437. // construct the array that will match the exact record to update
  2438. $match = array(
  2439. $pkcol => $record_id,
  2440. );
  2441. // construct the array of values to be updated
  2442. $values = array(
  2443. 'type_id' => array(
  2444. 'cv_id' => array(
  2445. 'name' => $cv_name,
  2446. ),
  2447. 'name' => $property,
  2448. ),
  2449. 'value' => $value,
  2450. );
  2451. return tripal_core_chado_update($basetable . 'prop', $match, $values);
  2452. }
  2453. /**
  2454. * Deletes a property for a given base table record using the property name
  2455. *
  2456. * @param $basetable
  2457. * The base table for which the property should be deleted. Thus to deleted a property
  2458. * for a feature the basetable=feature and property is deleted from featureprop
  2459. * @param $record_id
  2460. * The primary key of the basetable to delete a property for. This should be in integer.
  2461. * @param $property
  2462. * The cvterm name describing the type of property to be deleted
  2463. * @param $cv_name
  2464. * The name of the cv that the above cvterm is part of
  2465. *
  2466. * Note: The property to be deleted is select via the unique combination of $record_id and $property
  2467. *
  2468. * @return
  2469. * Return True on Delete and False otherwise
  2470. *
  2471. * @ingroup tripal_chado_api
  2472. */
  2473. function tripal_core_delete_property($basetable, $record_id, $property, $cv_name) {
  2474. // get the foreign key for this property table
  2475. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  2476. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  2477. // construct the array that will match the exact record to update
  2478. $match = array(
  2479. $fkcol => $record_id,
  2480. 'type_id' => array(
  2481. 'cv_id' => array(
  2482. 'name' => $cv_name,
  2483. ),
  2484. 'name' => $property,
  2485. ),
  2486. );
  2487. return tripal_core_chado_delete($basetable . 'prop', $match);
  2488. }
  2489. /**
  2490. * Deletes a property using the property ID
  2491. *
  2492. * @param $basetable
  2493. * The base table for which the property should be deleted. Thus to deleted a property
  2494. * for a feature the basetable=feature and property is deleted from featureprop
  2495. * @param $record_id
  2496. * The primary key of the basetable to delete a property for. This should be in integer.
  2497. *
  2498. * @return
  2499. * Return True on Delete and False otherwise
  2500. *
  2501. * @ingroup tripal_chado_api
  2502. */
  2503. function tripal_core_delete_property_by_id($basetable, $record_id) {
  2504. // get the foreign key for this property table
  2505. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  2506. $pkcol = $table_desc['primary key'][0];
  2507. // construct the array that will match the exact record to update
  2508. $match = array(
  2509. $pkcol => $record_id,
  2510. );
  2511. return tripal_core_chado_delete($basetable . 'prop', $match);
  2512. }
  2513. /**
  2514. * This function is typically used in the '.install' file for a Tripal module
  2515. * Each module should call this function during installation to create
  2516. * the module data directory which is sites/default/files/tripal/[module_name]
  2517. * for default Drupal settings. This directory can then be used by the module
  2518. * for storing files.
  2519. *
  2520. * @param $module_name
  2521. * the name of the module being installed.
  2522. *
  2523. * @returns
  2524. * nothing
  2525. *
  2526. * @ingroup tripal_files_api
  2527. */
  2528. function tripal_create_moddir($module_name) {
  2529. // make the data directory for this module
  2530. $data_dir = file_directory_path() . "/tripal/$module_name";
  2531. if (!file_check_directory($data_dir, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
  2532. $message = "Cannot create directory $data_dir. This module may not ".
  2533. "behave correctly without this directory. Please create ".
  2534. "the directory manually or fix the problem and reinstall.";
  2535. drupal_set_message(check_plain(t($message)), 'error');
  2536. watchdog('tripal_core', $message, array(), WATCHDOG_ERROR);
  2537. }
  2538. }
  2539. /**
  2540. * Each Tripal module has a unique data directory which was creatd using the
  2541. * tripal_create_moddir function during installation. This function
  2542. * retrieves the directory path.
  2543. *
  2544. * @param $module_name
  2545. * The name of the module
  2546. *
  2547. * @returns
  2548. * The path within the Drupal installation where the data directory resides
  2549. * @ingroup tripal_files_api
  2550. */
  2551. function tripal_get_moddir($module_name) {
  2552. $data_dir = file_directory_path() . "/tripal/$module_name";
  2553. return $data_dir;
  2554. }
  2555. /**
  2556. * Set the Tripal Database
  2557. *
  2558. * The tripal_db_set_active function is used to prevent namespace collisions
  2559. * when chado and drupal are installed in the same database but in different
  2560. * schemas. It is also used for backwards compatibility with older versions
  2561. * of tripal or in cases where chado is located outside of the Drupal database.
  2562. *
  2563. * @ingroup tripal_chado_api
  2564. */
  2565. function tripal_db_set_active($dbname = 'default') {
  2566. global $db_url, $db_type, $active_db;
  2567. $chado_exists = 0;
  2568. // only postgres can support search paths. So if this is MysQL then
  2569. // just run the normal tripal_db_set_active function.
  2570. if (strcmp($db_type, 'pgsql')==0) {
  2571. // if the 'chado' database is in the $db_url variable then chado is
  2572. // not in the same Drupal database, so we don't need to set any
  2573. // search_path and can just change the database
  2574. if (is_array($db_url)) {
  2575. if (isset($db_url[$dbname])) {
  2576. return db_set_active($dbname);
  2577. }
  2578. }
  2579. // if this is the default database then set the search path and return
  2580. if (strcmp($dbname, 'default')==0) {
  2581. tripal_db_set_default_search_path();
  2582. return db_set_active($dbname);
  2583. }
  2584. // if the user requests a database other than the default
  2585. // then we need to try and set the chado search path. This
  2586. // only works if Chado is local to the Drpual database. If it
  2587. // fails then do nothing.
  2588. else {
  2589. if (tripal_db_set_chado_search_path($dbname)) {
  2590. // if the chado schema is local to Drupal then
  2591. // just return the active database.
  2592. return 'default';
  2593. }
  2594. else {
  2595. watchdog('tripal_core', "Cannot set 'search_path' variable for Postgres to %dbname",
  2596. array('%dbname' => $dbname), WATCHDOG_ERROR);
  2597. }
  2598. }
  2599. }
  2600. // a non postgres database
  2601. else {
  2602. return db_set_active($dbname);
  2603. }
  2604. }
  2605. /**
  2606. * Gets the current search_path for PostgreSQL
  2607. *
  2608. * @ingroup tripal_chado_api
  2609. */
  2610. function tripal_db_get_search_path() {
  2611. $path = db_fetch_object(db_query("show search_path"));
  2612. return $path->search_path;
  2613. }
  2614. /**
  2615. * Set the chado search_path for PostgreSQL
  2616. *
  2617. * Sets the database search_path for postgreSQL to the
  2618. * chado schema.
  2619. *
  2620. * @ingroup tripal_chado_api
  2621. */
  2622. function tripal_db_set_chado_search_path($dbname) {
  2623. // check to make sure the chado schema exists
  2624. $chado_exists = variable_get('chado_schema_exists', FALSE);
  2625. if (!$chado_exists) {
  2626. $chado_exists = tripal_core_chado_schema_exists();
  2627. }
  2628. // here we make the assumption that the default database schema is
  2629. // 'public'. This will most likely always be the case but if not,
  2630. // then this code will break
  2631. if ($chado_exists) {
  2632. db_query('set search_path to %s', "$dbname,public");
  2633. return TRUE;
  2634. }
  2635. else {
  2636. return FALSE;
  2637. }
  2638. }
  2639. /**
  2640. * Set the default search_path for PostgreSQL
  2641. *
  2642. * Sets the database search_path for postgreSQL to the
  2643. * default schema.
  2644. *
  2645. * @ingroup tripal_chado_api
  2646. */
  2647. function tripal_db_set_default_search_path() {
  2648. // we make the assumption that the default schema is 'public'.
  2649. $chado_exists = variable_get('chado_schema_exists', FALSE);
  2650. if ($chado_exists) {
  2651. db_query('set search_path to %s', 'public,chado');
  2652. }
  2653. else {
  2654. db_query('set search_path to %s', 'public');
  2655. }
  2656. }
  2657. /**
  2658. * Indicates if the SQL statement is prepapred
  2659. *
  2660. * @param $statement_name
  2661. * The name of the statement to check if it is prepared.
  2662. *
  2663. * @return
  2664. * TRUE if the statement is preapred, FALSE otherwise
  2665. */
  2666. function tripal_core_is_sql_prepared($statement_name) {
  2667. global $prepared_statements;
  2668. // check to see if the statement is prepared already
  2669. if (in_array($statement_name, $prepared_statements)) {
  2670. return TRUE;
  2671. }
  2672. // @coder-ignore: acting on postgres tables rather then drupal schema therefore, table prefixing does not apply
  2673. $sql = "SELECT name FROM pg_prepared_statements WHERE name = '%s'";
  2674. // do not use 'chado_query' here or it causes memory-leaks
  2675. $result = db_fetch_object(db_query($sql, $statement_name));
  2676. if ($result) {
  2677. return TRUE;
  2678. }
  2679. return FALSE;
  2680. }
  2681. /**
  2682. * Prepare a chado query
  2683. *
  2684. * @param $statement_name
  2685. * The name of the prepared statement
  2686. * @param $psql
  2687. * The SQL statement to be executed via chado_query.
  2688. * Should be of the form PREPARE <statement name> AS <SQL Statement to be prepared>
  2689. * @param $args
  2690. * An array of arguements required to execute the prepared statement. The keys of
  2691. * the array should correspond to the $\d in the prepare statement and the value should
  2692. * be the type of value needed (ie: text, int, etc.)
  2693. */
  2694. function tripal_core_chado_prepare($statement_name, $psql, $args) {
  2695. global $persistent_chado;
  2696. global $prepared_statements;
  2697. if (!$persistent_chado) {
  2698. watchdog('tripal_core', "chado_prepare: not able to prepare '%name' statement as no persistent connection is available", array('%name' => $statement_name, '%sql' => $psql), WATCHDOG_ERROR);
  2699. return FALSE;
  2700. }
  2701. // Check to see if this statement was already prepared
  2702. if (tripal_core_is_sql_prepared($statement_name)) {
  2703. // check that the arguments are the same
  2704. $prepared_args = $prepared_statements[$statement_name]['prepared_args'];
  2705. $prepared_sql = $prepared_statements[$statement_name]['prepared_sql'];
  2706. if ($prepared_args == $args) {
  2707. // This statement is already prepared
  2708. return TRUE;
  2709. }
  2710. else {
  2711. // Although a statement with this name is already prepared it is not the same!
  2712. watchdog('tripal_core', "chado_prepare: '%name' statement already prepared with different arguments! ".
  2713. "You want to prepare \n%sql\n with \n%values\n and the existing statement is \n%esql\n with \n%existing",
  2714. array('%name' => $statement_name, '%sql' => $psql, '%values' => print_r($args, TRUE), '%esql' => $prepared_sql,
  2715. '%existing' => print_r($prepared_args, TRUE)), WATCHDOG_ERROR);
  2716. return FALSE;
  2717. }
  2718. }
  2719. $status = chado_query($psql);
  2720. if (!$status) {
  2721. watchdog('tripal_core', "chado_prepare: not able to prepare '%name' statement for: %sql", array('%name' => $statement_name, '%sql' => $psql), WATCHDOG_ERROR);
  2722. return FALSE;
  2723. }
  2724. else {
  2725. $prepared_statements[$statement_name] = array();
  2726. $prepared_statements[$statement_name]['prepared_args'] = $args;
  2727. $prepared_statements[$statement_name]['prepared_sql'] = $psql;
  2728. return TRUE;
  2729. }
  2730. }
  2731. /**
  2732. * Execute a prepared statement with the supplied values
  2733. *
  2734. * @param $statement_name
  2735. * The name of the prepared statement
  2736. * @param $sql
  2737. * The SQL to execute using chado query.
  2738. * Should be of the form EXECUTE <statement_name> (<arg1>,<arg2>...<argn>)
  2739. * @param $values
  2740. * An array of values in the execute sql statement
  2741. */
  2742. function tripal_core_chado_execute_prepared($statement_name, $sql, $values) {
  2743. global $prepared_statements;
  2744. if (!tripal_core_is_sql_prepared($statement_name)) {
  2745. watchdog('tripal_core', "tripal_core_chado_execute_prepared: Cannot execute an unprepared statement: '%name'", array('%name' => $statement_name), WATCHDOG_ERROR);
  2746. return FALSE;
  2747. }
  2748. // Before Executing, Ensure that all the values are supplied
  2749. $required_values = $prepared_statements[$statement_name]['prepared_args'];
  2750. if (!$required_values) {
  2751. watchdog('tripal_core', "tripal_core_chado_execute_prepared: missing prepare arguments for this statement: '%name'", array('%name' => $statement_name), WATCHDOG_ERROR);
  2752. return FALSE;
  2753. }
  2754. if (sizeof($required_values) == sizeof($values)) {
  2755. $error = FALSE;
  2756. foreach ($values as $k => $v) {
  2757. if (isset($required_values[$k])) {
  2758. switch ($required_values[$k]) {
  2759. case 'text':
  2760. $check = is_string($v);
  2761. if ($v != '' and !$check) {
  2762. watchdog('tripal_core', "chado_execute_prepared: wrong argument type supplied for '%name' statement, field %k. Expected %required but recieved '%value'",
  2763. array('%name' => $statement_name, '%k' => $k+1, '%required' => $required_values[$k], '%value' => print_r($v, TRUE)), WATCHDOG_ERROR);
  2764. return FALSE;
  2765. }
  2766. break;
  2767. case 'int':
  2768. $check = is_numeric($v);
  2769. if (!$check) {
  2770. watchdog('tripal_core', "chado_execute_prepared: wrong argument type supplied for '%name' statement, field %k. Expected %required but recieved '%value'",
  2771. array('%name' => $statement_name, '%k' => $k+1, '%required' => $required_values[$k], '%value' => print_r($v, TRUE)), WATCHDOG_ERROR);
  2772. return FALSE;
  2773. }
  2774. break;
  2775. case 'bool':
  2776. if ($v != 'TRUE' and $v != 'FALSE') {
  2777. watchdog('tripal_core', "chado_execute_prepared: wrong argument type supplied for '%name' statement, field %k. Expected %required but recieved '%value'",
  2778. array('%name' => $statement_name, '%k' => $k+1, '%required' => $required_values[$k], '%value' => print_r($v, TRUE)), WATCHDOG_ERROR);
  2779. return FALSE;
  2780. }
  2781. break;
  2782. case 'numeric':
  2783. $check = is_numeric($v);
  2784. if (!$check) {
  2785. watchdog('tripal_core', "chado_execute_prepared: wrong argument type supplied for '%name' statement, field %k. Expected %required but recieved '%value'",
  2786. array('%name' => $statement_name, '%k' => $k+1, '%required' => $required_values[$k], '%value' => print_r($v, TRUE)), WATCHDOG_ERROR);
  2787. return FALSE;
  2788. }
  2789. break;
  2790. default:
  2791. watchdog('tripal_core', "chado_execute_prepared: unsupported argument type (supplied for '%name' statement %type)",
  2792. array('%name' => $statement_name, '%type' => $required_values[$k]), WATCHDOG_WARNING);
  2793. break;
  2794. }
  2795. }
  2796. else {
  2797. watchdog('tripal_core', "chado_execute_prepared: wrong number of arguments supplied for '%name' statement. Expected %required but recieved %values",
  2798. array('%name' => $statement_name, '%required' => print_r($required_values, TRUE), '%values' => print_r($values, TRUE)), WATCHDOG_ERROR);
  2799. return FALSE;
  2800. }
  2801. }
  2802. // Since all values are supplied, execute
  2803. $resource = chado_query($sql, $values);
  2804. return $resource;
  2805. }
  2806. else {
  2807. watchdog('tripal_core', "chado_execute_prepared: wrong number of arguments supplied for '%name' statement. ' .
  2808. 'Expected %required but recieved %values. Statement: %statement.",
  2809. array('%name' => $statement_name, '%required' => print_r($required_values, TRUE),
  2810. '%values' => print_r($values, TRUE), '%statement' => $prepared_statements[$statement_name]['prepared_sql']), WATCHDOG_ERROR);
  2811. return FALSE;
  2812. }
  2813. }
  2814. /**
  2815. * Clears prepared statements to avoid conflicts
  2816. *
  2817. * If no statement_name_regex is supplied then it clears ALL prepared statements;
  2818. * Otherwise, it clears prepared statement names that match the regex provided
  2819. */
  2820. function tripal_core_chado_clear_prepared ($statement_name_regex = NULL) {
  2821. global $prepared_statements;
  2822. if ($statement_name_regex) {
  2823. $resource = chado_query("SELECT * FROM pg_catalog.pg_prepared_statements WHERE name~'%s'",$statement_name_regex);
  2824. while ($r = db_fetch_object($resource)) {
  2825. $k = array_search($r->name, $prepared_statements);
  2826. unset($prepared_statements[$k]);
  2827. chado_query('DEALLOCATE PREPARE %s',$r->name);
  2828. }
  2829. }
  2830. else {
  2831. $prepared_statements = array();
  2832. chado_query('DEALLOCATE PREPARE ALL');
  2833. }
  2834. }
  2835. /**
  2836. * Instantiate or Return a persistent chado connection. This should not be confused with
  2837. * PHP persistent connections. Here we use the drupal db_connect function to
  2838. *
  2839. * NOTE: cannot use $active_db since a new connection is created each time
  2840. * db_set_active() is called
  2841. *
  2842. * @return
  2843. * A postgresql connection object which can be used by pg_prepare, pg_execute, etc.
  2844. */
  2845. function tripal_db_persistent_chado() {
  2846. global $db_url;
  2847. global $persistent_chado;
  2848. // get connection if it already exists otherwise we need to set it
  2849. if ($persistent_chado) {
  2850. return $persistent_chado;
  2851. }
  2852. else {
  2853. if (is_array($db_url) && isset($db_url['chado'])) {
  2854. $connection = db_connect($db_url['chado']);
  2855. if (!$connection) {
  2856. watchdog('tripal_core', "Could not create persistant connection", array(), WATCHDOG_ERROR);
  2857. return FALSE;
  2858. }
  2859. $persistent_chado = $connection;
  2860. }
  2861. else {
  2862. if (is_array($db_url)) {
  2863. $connection = db_connect($db_url['default']);
  2864. }
  2865. else {
  2866. $connection = db_connect($db_url);
  2867. }
  2868. if (!$connection) {
  2869. $persistent_chado = NULL;
  2870. watchdog('tripal_core', "Could not create persistant connection", array(), WATCHDOG_ERROR);
  2871. return FALSE;
  2872. }
  2873. $persistent_chado = $connection;
  2874. }
  2875. return $connection;
  2876. }
  2877. return FALSE;
  2878. }
  2879. /**
  2880. * Release a persistent chado connection
  2881. */
  2882. function tripal_db_release_persistent_chado() {
  2883. $persistent_chado = NULL;
  2884. }
  2885. /**
  2886. * Start a transaction block. Ensures the use of a persistent chado connection
  2887. */
  2888. function tripal_db_start_transaction() {
  2889. $connection = tripal_db_persistent_chado();
  2890. if ($connection) {
  2891. chado_query("BEGIN");
  2892. return $connection;
  2893. }
  2894. return FALSE;
  2895. }
  2896. /**
  2897. * Set a savepoint to roll the current transaction back to if an error is encountered
  2898. */
  2899. function tripal_db_set_savepoint_transaction($savepoint, $release = FALSE) {
  2900. // Postgresql requires a savepoint of the same name to be unset before re-use
  2901. if ($release) {
  2902. chado_query("RELEASE SAVEPOINT %s", $savepoint);
  2903. }
  2904. chado_query("SAVEPOINT %s", $savepoint);
  2905. }
  2906. /**
  2907. * Commit changes made during the current transaction
  2908. */
  2909. function tripal_db_commit_transaction() {
  2910. chado_query("COMMIT");
  2911. }
  2912. /**
  2913. * Rollback changes.
  2914. *
  2915. * If $savepoint is NULL then rollback to the beginning of the transaction,
  2916. * Otherwise, rollback to the point at which the named $savepoint was created
  2917. *
  2918. * @param $savepoint
  2919. * The name of the saved point in the transaction to rollback to
  2920. */
  2921. function tripal_db_rollback_transaction($savepoint = NULL, $commit = TRUE) {
  2922. if ($savepoint) {
  2923. chado_query("ROLLBACK TO SAVEPOINT %s", $savepoint);
  2924. }
  2925. else {
  2926. chado_query("ROLLBACK");
  2927. }
  2928. if ($commit) {
  2929. tripal_db_commit_transaction();
  2930. }
  2931. }
  2932. /**
  2933. * Purpose: Get max rank for a given set of criteria
  2934. * This function was developed with the many property tables in chado in mind
  2935. *
  2936. * @param $tablename
  2937. * The name of the chado table you want to select the max rank from this table must contain a
  2938. * rank column of type integer
  2939. * @param $where_options
  2940. * where options should include the id and type for that table to correctly
  2941. * group a set of records together where the only difference are the value and rank
  2942. * @code
  2943. * array(
  2944. * <column_name> => array(
  2945. * 'type' => <type of column: INT/STRING>,
  2946. * 'value' => <the value you want to filter on>,
  2947. * 'exact' => <if TRUE use =; if FALSE use ~>,
  2948. * )
  2949. * )
  2950. * @endcode
  2951. * @return the maximum rank
  2952. *
  2953. * @ingroup tripal_chado_api
  2954. */
  2955. function tripal_get_max_chado_rank($tablename, $where_options) {
  2956. $where= array();
  2957. //generate the where clause from supplied options
  2958. // the key is the column name
  2959. foreach ($where_options as $key => $val_array) {
  2960. if (preg_match('/INT/', $val_array['type'])) {
  2961. $where[] = $key . "=" . $val_array['value'];
  2962. }
  2963. else {
  2964. if ($val_array['exact']) {
  2965. $operator='=';
  2966. }
  2967. else {
  2968. $operator='~';
  2969. }
  2970. $where[] = $key . $operator . "'" . $val_array['value'] . "'";
  2971. }
  2972. }
  2973. $previous_db = tripal_db_set_active('chado');
  2974. $result = db_fetch_object(db_query("SELECT max(rank) as max_rank, count(rank) as count FROM %s WHERE %s",
  2975. $tablename, implode(' AND ', $where)));
  2976. tripal_db_set_active($previous_db);
  2977. //drupal_set_message("Max Rank Query=SELECT max(rank) as max_rank, count(rank) as count FROM ".$tablename." WHERE ".implode(' AND ',$where));
  2978. if ($result->count > 0) {
  2979. return $result->max_rank;
  2980. }
  2981. else {
  2982. return -1;
  2983. }
  2984. }
  2985. /**
  2986. * Retrieves the schema in an array for the specified custom table.
  2987. *
  2988. * @param $table
  2989. * The name of the table to create.
  2990. *
  2991. * @return
  2992. * A Drupal-style Schema API array definition of the table. Returns
  2993. * FALSE on failure.
  2994. *
  2995. * @ingroup tripal_core_api
  2996. */
  2997. function tripal_get_chado_custom_schema($table) {
  2998. $sql = "SELECT schema FROM {tripal_custom_tables} WHERE table_name = '%s'";
  2999. $custom = db_fetch_object(db_query($sql, $table));
  3000. if (!$custom) {
  3001. return FALSE;
  3002. }
  3003. else {
  3004. return unserialize($custom->schema);
  3005. }
  3006. }
  3007. /**
  3008. * Check that the Chado schema exists
  3009. *
  3010. * @return
  3011. * TRUE/FALSE depending upon whether it exists
  3012. */
  3013. function tripal_core_chado_schema_exists() {
  3014. $exists = variable_get('chado_schema_exists', FALSE);
  3015. if (!$exists) {
  3016. // This is postgresql-specific code to check the existence of the chado schema
  3017. // @coder-ignore: acting on pg_catalog schema rather then drupal schema therefore, table prefixing does not apply
  3018. $sql = "SELECT nspname FROM pg_catalog.pg_namespace WHERE nspname = 'chado'";
  3019. if (db_fetch_object(db_query($sql))) {
  3020. variable_set('chado_schema_exists', TRUE);
  3021. return TRUE;
  3022. }
  3023. else {
  3024. return FALSE;
  3025. }
  3026. }
  3027. return TRUE;
  3028. }
  3029. /**
  3030. * Check that any given schema exists
  3031. *
  3032. * @param $schema
  3033. * The name of the schema to check the existence of
  3034. *
  3035. * @return
  3036. * TRUE/FALSE depending upon whether or not the schema exists
  3037. *
  3038. * @ingroup tripal_chado_api
  3039. */
  3040. function tripal_core_schema_exists($schema) {
  3041. // check that the chado schema now exists
  3042. $sql = "SELECT nspname
  3043. FROM pg_namespace
  3044. WHERE has_schema_privilege(nspname, 'USAGE') and nspname = '%s'
  3045. ORDER BY nspname";
  3046. $name = db_fetch_object(db_query($sql, $schema));
  3047. if (strcmp($name->nspname, $schema) != 0) {
  3048. return FALSE;
  3049. }
  3050. return TRUE;
  3051. }
  3052. /**
  3053. * Retrieves the list tables in the Chado schema. By default it only retursn
  3054. * the default Chado tables, but may also return custom tables added to the
  3055. * Chado schema as well.
  3056. *
  3057. * @param $include_custom
  3058. * Optional. Set as TRUE to include any custom tables created in the
  3059. * Chado schema. Custom tables are added to Chado using the
  3060. * tripal_core_chado_create_table() function.
  3061. *
  3062. * @returns
  3063. * An associative array where the key and value pairs are the Chado table names.
  3064. *
  3065. * @ingroup tripal_core_api
  3066. */
  3067. function tripal_core_get_chado_tables($include_custom = NULL) {
  3068. // first get the chado version that is installed
  3069. $v = tripal_core_get_chado_version();
  3070. $tables = array();
  3071. if ($v == '1.2') {
  3072. $tables_v1_2 = tripal_core_chado_get_v1_2_tables();
  3073. foreach ($tables_v1_2 as $table) {
  3074. $tables[$table] = $table;
  3075. }
  3076. }
  3077. if ($v == '1.11' or $v == '1.11 or older') {
  3078. $tables_v1_11 = tripal_core_chado_get_v1_11_tables();
  3079. foreach ($tables_v1_11 as $table) {
  3080. $tables[$table] = $table;
  3081. }
  3082. }
  3083. // now add in the custom tables too if requested
  3084. if ($include_custom) {
  3085. $sql = "SELECT table_name FROM {tripal_custom_tables}";
  3086. $resource = db_query($sql);
  3087. while ($r = db_fetch_object($resource)) {
  3088. $tables[$r->table_name] = $r->table_name;
  3089. }
  3090. }
  3091. asort($tables);
  3092. return $tables;
  3093. }
  3094. /**
  3095. * Sets a Drupal variable with the current version of Chado. This variable
  3096. * can then be queried later using the tripal_core_get_chado_Version
  3097. *
  3098. * @returns
  3099. * The version of Chado
  3100. *
  3101. * @ingroup tripal_core_api
  3102. */
  3103. function tripal_core_set_chado_version() {
  3104. global $db_url;
  3105. // check that Chado is installed if not return 'uninstalled as the version'
  3106. $chado_exists = tripal_core_chado_schema_exists();
  3107. if (!$chado_exists) {
  3108. // if it's not in the drupal database check to see if it's specified in the $db_url
  3109. // in the settings.php
  3110. if (!is_array($db_url) or !array_key_exists('chado', $db_url)) {
  3111. // if it's not in the drupal database or specified in the $db_url then
  3112. // return uninstalled as the version
  3113. return 'not installed';
  3114. }
  3115. }
  3116. // if the table doesn't exist then we don't know what version but we know
  3117. // it must be 1.11 or older.
  3118. $previous_db = tripal_db_set_active('chado');
  3119. $prop_exists = db_table_exists('chadoprop');
  3120. tripal_db_set_active($previous_db);
  3121. if (!$prop_exists) {
  3122. return "1.11 or older";
  3123. }
  3124. // we can't use the Tripal API to query this table
  3125. // because the Tripal API depends on this function to
  3126. // tell it the version. So, we need a typical SQL statement
  3127. $sql = "SELECT value "
  3128. ."FROM chadoprop CP "
  3129. ." INNER JOIN cvterm CVT on CVT.cvterm_id = CP.type_id "
  3130. ." INNER JOIN cv CV on CVT.cv_id = CV.cv_id "
  3131. ."WHERE CV.name = 'chado_properties' and CVT.name = 'version'";
  3132. $previous_db = tripal_db_set_active('chado');
  3133. $v = db_fetch_object(db_query($sql));
  3134. tripal_db_set_active($previous_db);
  3135. // if we don't have a version in the chadoprop table then it must be
  3136. // v1.11 or older
  3137. if (!$v->value) {
  3138. variable_set('chado_version', "1.11 or older");
  3139. return "1.11 or older";
  3140. }
  3141. variable_set('chado_version', $v->value);
  3142. return $v->value;
  3143. }
  3144. /**
  3145. * Returns the version number of the currently installed Chado instance.
  3146. * It can return the real or effective version.
  3147. *
  3148. * @param $exact
  3149. * Set this argument to 1 to retrieve the exact version that is installed.
  3150. * Otherwise, this function will set the version to the nearest 'tenth'.
  3151. * Chado versioning numbers in the hundreds represent changes to the
  3152. * software and not the schema. Changes in the tenth's represent changes
  3153. * in the schema.
  3154. *
  3155. * @param $warn_if_unsupported
  3156. * If the currently installed version of Chado is not supported by Tripal
  3157. * the generatea a Drupal warning.
  3158. *
  3159. * @returns
  3160. * The version of Chado
  3161. *
  3162. * @ingroup tripal_core_api
  3163. */
  3164. function tripal_core_get_chado_version($exact = FALSE, $warn_if_unsupported = FALSE) {
  3165. // first get the chado version that is installed
  3166. $exact_version = variable_get('chado_version', '');
  3167. if (!$exact_version) {
  3168. $exact_version = tripal_core_set_chado_version();
  3169. }
  3170. // Tripal only supports v1.11 or newer.. really this is the same as v1.1
  3171. // but at the time the v1.11 schema API was written we didn't know that so
  3172. // we'll return the version 1.11 so the schema API will work.
  3173. if (strcmp($exact_version, '1.11 or older') == 0) {
  3174. $exact_version = "1.11";
  3175. if ($warn_if_unsupported) {
  3176. drupal_set_message(t("WARNING: Tripal does not fully support Chado version less than v1.1. If you are certain this is v1.1
  3177. of if Chado was installed using an earlier version of Tripal then all is well. If not please upgrade to v1.1 or later"),
  3178. 'warning');
  3179. }
  3180. }
  3181. // if not returing an exact version, return the version to the nearest 10th.
  3182. // return 1.2 for all versions of 1.2x
  3183. $effective_version = $exact_version;
  3184. if (preg_match('/^1\.2\d+$/', $effective_version)) {
  3185. $effective_version = "1.2";
  3186. }
  3187. if ($warn_if_unsupported and ($effective_version != 1.11 and $effective_version != 1.2 and $effective_version != 'not installed')) {
  3188. drupal_set_message(t("WARNING: The currently installed version of Chado, v$exact_version, is not fully compatible with Tripal."), 'warning');
  3189. }
  3190. // if the callee has requested the exact version then return it
  3191. if ($exact) {
  3192. return $exact_version;
  3193. }
  3194. return $effective_version;
  3195. }
  3196. /**
  3197. * Retrieves the chado tables Schema API array.
  3198. *
  3199. * @param $table
  3200. * The name of the table to retrieve. The function will use the appopriate
  3201. * Tripal chado schema API hooks (e.g. v1.11 or v1.2).
  3202. *
  3203. * @returns
  3204. * A Drupal Schema API array defining the table.
  3205. *
  3206. * @ingroup tripal_core_api
  3207. */
  3208. function tripal_core_get_chado_table_schema($table) {
  3209. // first get the chado version that is installed
  3210. $v = tripal_core_get_chado_version();
  3211. // get the table array from the proper chado schema
  3212. $v = preg_replace("/\./", "_", $v); // reformat version for hook name
  3213. $table_arr = module_invoke_all("chado_schema_v" . $v . "_" . $table);
  3214. // if the table_arr is empty then maybe this is a custom table
  3215. if (!is_array($table_arr) or count($table_arr) == 0) {
  3216. $table_arr = tripal_get_chado_custom_schema($table);
  3217. }
  3218. return $table_arr;
  3219. }
  3220. /**
  3221. * This function will delete Drupal nodes for any sync'ed table (e.g.
  3222. * feature, organism, analysis, stock, library) if the chado record has been
  3223. * deleted or the entry in the chado_[table] table has been removed.
  3224. *
  3225. * @param $table
  3226. * The name of the table that corresonds to the node type we want to clean up.
  3227. * @param $job_id
  3228. * This should be the job id from the Tripal jobs system. This function
  3229. * will update the job status using the provided job ID.
  3230. *
  3231. * @ingroup tripal_core_api
  3232. */
  3233. function tripal_core_clean_orphaned_nodes($table, $job_id) {
  3234. $count = 0;
  3235. // build the SQL statments needed to check if nodes point to valid analyses
  3236. $dsql = "SELECT * FROM {node} WHERE type = 'chado_%s' order by nid";
  3237. $nsql = "SELECT * FROM {node} WHERE nid = %d";
  3238. $csql = "SELECT * FROM {chado_%s} where nid = %d ";
  3239. $clsql= "SELECT * FROM {chado_%s}";
  3240. $lsql = "SELECT * FROM %s where %s_id = %d ";
  3241. // load into nodes array
  3242. print "Getting nodes\n";
  3243. $nodes = array();
  3244. $res = db_query($dsql, $table);
  3245. while ($node = db_fetch_object($res)) {
  3246. $nodes[$count] = $node;
  3247. $count++;
  3248. }
  3249. // load the chado_$table into an array
  3250. print "Getting chado_$table\n";
  3251. $cnodes = array();
  3252. $res = db_query($clsql, $table);
  3253. while ($node = db_fetch_object($res)) {
  3254. $cnodes[$count] = $node;
  3255. $count++;
  3256. }
  3257. $interval = intval($count * 0.01);
  3258. if ($interval < 1) {
  3259. $interval = 1;
  3260. }
  3261. // iterate through all of the chado_$table entries and remove those
  3262. // that don't have a node or don't have a $table record in chado.libary
  3263. print "Verifying all chado_$table Entries\n";
  3264. $deleted = 0;
  3265. foreach ($cnodes as $nid) {
  3266. // update the job status every 1% analyses
  3267. if ($job_id and $i % $interval == 0) {
  3268. tripal_job_set_progress($job_id, intval(($i / $count) * 100));
  3269. }
  3270. // see if the node exits, if not remove the entry from the chado_$table table
  3271. $node = db_fetch_object(db_query($nsql, $nid->nid));
  3272. if (!$node) {
  3273. $deleted++;
  3274. db_query("DELETE FROM {chado_%s} WHERE nid = %d", $table, $nid->nid);
  3275. $message = "chado_$table missing node.... DELETING: $nid->nid";
  3276. watchdog('tripal_core', $message, array(), WATCHDOG_WARNING);
  3277. }
  3278. // see if the record in chado exist, if not remove the entry from the chado_$table
  3279. $table_id = $table . "_id";
  3280. $record = db_fetch_object(chado_query($lsql, $table, $table, $nid->$table_id));
  3281. if (!$record) {
  3282. $deleted++;
  3283. db_query("DELETE FROM {chado_%s} WHERE %s_id = '%d'", $table, $table, $nid->$table_id);
  3284. $message = "chado_$table missing $table.... DELETING entry.";
  3285. watchdog('tripal_core', $message, array(), WATCHDOG_WARNING);
  3286. }
  3287. $i++;
  3288. }
  3289. print "\t$deleted chado_$table entries missing either a node or chado entry.\n";
  3290. // iterate through all of the nodes and delete those that don't
  3291. // have a corresponding entry in chado_$table
  3292. $deleted = 0;
  3293. foreach ($nodes as $node) {
  3294. // update the job status every 1% libraries
  3295. if ($job_id and $i % $interval == 0) {
  3296. tripal_job_set_progress($job_id, intval(($i / $count) * 100));
  3297. }
  3298. // check to see if the node has a corresponding entry
  3299. // in the chado_$table table. If not then delete the node.
  3300. $link = db_fetch_object(db_query($csql, $table, $node->nid));
  3301. if (!$link) {
  3302. if (node_access('delete', $node)) {
  3303. $deleted++;
  3304. $message = "Node missing in chado_$table table.... DELETING node $node->nid";
  3305. watchdog("tripal_core", $message, array(), WATCHDOG_WARNING);
  3306. node_delete($node->nid);
  3307. }
  3308. else {
  3309. $message = "Node missing in chado_$table table.... but cannot delete due to improper permissions (node $node->nid)";
  3310. watchdog("tripal_core", $message, array(), WATCHDOG_WARNING);
  3311. }
  3312. }
  3313. $i++;
  3314. }
  3315. print "\t$deleted nodes did not have corresponding chado_$table entries.\n";
  3316. return '';
  3317. }
  3318. /**
  3319. * Check whether chado is installed (either in the same or a different database)
  3320. *
  3321. * @return
  3322. * TRUE/FALSE depending upon whether chado is installed.
  3323. *
  3324. * @ingroup tripal_chado_api
  3325. */
  3326. function tripal_core_is_chado_installed() {
  3327. global $db_url, $db_type;
  3328. // first check if chado is in the db_url of the
  3329. // settings.php file
  3330. if (is_array($db_url)) {
  3331. if (isset($db_url['chado'])) {
  3332. return TRUE;
  3333. }
  3334. }
  3335. // check to make sure the chado schema exists
  3336. return tripal_core_chado_schema_exists();
  3337. }
  3338. /**
  3339. * Check whether chado is installed local to the Drupal database
  3340. * in its own Chado schema.
  3341. *
  3342. * @return
  3343. * TRUE/FALSE depending upon whether chado is local.
  3344. *
  3345. * @ingroup tripal_chado_api
  3346. */
  3347. function tripal_core_is_chado_local() {
  3348. global $db_url, $db_type;
  3349. $is_installed = tripal_core_is_chado_installed();
  3350. if ($is_installed) {
  3351. if (is_array($db_url)) {
  3352. if (isset($db_url['chado'])) {
  3353. return FALSE;
  3354. }
  3355. }
  3356. return TRUE;
  3357. }
  3358. return FALSE;
  3359. }