tripal_core.api.inc 127 KB

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