tripal_core.api.inc 116 KB

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