tripal_core.api.inc 135 KB

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