tripal_core.api.inc 113 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080
  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_last_insert_id($table, $field);
  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. *
  825. * Example usage:
  826. * @code
  827. * $columns = array('feature_id', 'name');
  828. * $values = array(
  829. * 'organism_id' => array(
  830. * 'genus' => 'Citrus',
  831. * 'species' => array('sinensis', 'clementina'),
  832. * ),
  833. * 'uniquename' => 'orange1.1g000034m.g',
  834. * 'type_id' => array (
  835. * 'cv_id' => array (
  836. * 'name' => 'sequence',
  837. * ),
  838. * 'name' => 'gene',
  839. * 'is_obsolete' => 0
  840. * ),
  841. * );
  842. * $options = array(
  843. * 'statement_name' => 'sel_feature_genus_species_cvname'
  844. * 'order_by' => array(
  845. * 'name' => 'ASC'
  846. * ),
  847. * );
  848. * $result = tripal_core_chado_select('feature',$columns,$values,$options);
  849. * @endcode
  850. * The above code selects a record from the feature table using the three fields
  851. * that uniquely identify a feature. The $columns array simply lists the columns
  852. * to select. The $values array is nested such that the organism is identified by
  853. * way of the organism_id foreign key constraint by specifying the genus and
  854. * species. The cvterm is also specified using its foreign key and the cv_id
  855. * for the cvterm is nested as well. In the example above, two different species
  856. * are allowed to match
  857. *
  858. * @ingroup tripal_chado_api
  859. */
  860. function tripal_core_chado_select($table, $columns, $values, $options = NULL) {
  861. // set defaults for options. If we don't set defaults then
  862. // we get memory leaks when we try to access the elements
  863. if (!is_array($options)) {
  864. $options = array();
  865. }
  866. if (!array_key_exists('case_insensitive_columns', $options)) {
  867. $options['case_insensitive_columns'] = array();
  868. }
  869. if (!array_key_exists('regex_columns', $options)) {
  870. $options['regex_columns'] = array();
  871. }
  872. if (!array_key_exists('order_by', $options)) {
  873. $options['order_by'] = array();
  874. }
  875. if (!array_key_exists('is_prepared', $options)) {
  876. $options['is_prepared'] = FALSE;
  877. }
  878. if (!array_key_exists('return_sql', $options)) {
  879. $options['return_sql'] = FALSE;
  880. }
  881. if (!array_key_exists('has_record', $options)) {
  882. $options['has_record'] = FALSE;
  883. }
  884. if (!array_key_exists('statement_name',$options)) {
  885. $options['statement_name'] = FALSE;
  886. }
  887. if (!array_key_exists('is_duplicate',$options)) {
  888. $options['is_duplicate'] = FALSE;
  889. }
  890. // if this is a prepared statement check to see if it has already been prepared
  891. $prepared = FALSE;
  892. if ($options['statement_name']) {
  893. $prepared = TRUE;
  894. // we need to get a persistent connection. If one exists this function
  895. // will not recreate it, but if not it will create one and store it in
  896. // a Drupal variable for reuse later.
  897. $connection = tripal_db_persistent_chado();
  898. }
  899. else {
  900. //print "NO STATEMENT (select): $table\n";
  901. //debug_print_backtrace();
  902. }
  903. // check that our columns and values arguments are proper arrays
  904. if (!is_array($columns)) {
  905. watchdog('tripal_core', 'the $columns argument for tripal_core_chado_select must be an array.');
  906. return FALSE;
  907. }
  908. if (!is_array($values)) {
  909. watchdog('tripal_core', 'the $values argument for tripal_core_chado_select must be an array.');
  910. return FALSE;
  911. }
  912. // get the table description
  913. $table_desc = tripal_core_get_chado_table_schema($table);
  914. $select = '';
  915. $from = '';
  916. $where = '';
  917. $args = array();
  918. // if the 'use_unique' option is turned on then we want
  919. // to remove all but unique keys
  920. if ($options['is_duplicate'] and array_key_exists('unique keys', $table_desc)) {
  921. $ukeys = $table_desc['unique keys'];
  922. // iterate through the unique constraints and reset the values and columns
  923. // arrays to only include these fields
  924. foreach ($ukeys as $cname => $fields) {
  925. $new_values = array();
  926. $new_columns = array();
  927. $new_options = array();
  928. $uq_sname = "uq_" . $table . "_";
  929. $has_pkey = 0;
  930. // include the primary key in the results returned
  931. if (array_key_exists('primary key', $table_desc)){
  932. $has_pkey = 1;
  933. $pkeys = $table_desc['primary key'];
  934. foreach ($pkeys as $index => $key) {
  935. array_push($new_columns, $key);
  936. }
  937. }
  938. foreach ($fields as $field) {
  939. if (array_key_exists($field, $values)) {
  940. $new_values[$field] = $values[$field];
  941. $uq_sname .= substr($field, 0, 2);
  942. // if there is no primary key then use the unique contraint fields
  943. if (!$has_pkey) {
  944. array_push($new_columns, $field);
  945. }
  946. }
  947. elseif (array_key_exists('default', $table_desc['fields'][$field])) {
  948. $new_values[$field] = $table_desc['fields'][$field]['default'];
  949. $uq_sname .= substr($field, 0, 2);
  950. if (!$has_pkey){
  951. array_push($new_columns, $field);
  952. }
  953. }
  954. else {
  955. return FALSE;
  956. }
  957. }
  958. $new_options['statement_name'] = $uq_sname;
  959. $results = tripal_core_chado_select($table, $new_columns, $new_values, $new_options);
  960. // if we have a duplicate record then return the results
  961. if (count($results) > 0) {
  962. return $results;
  963. }
  964. }
  965. return FALSE;
  966. }
  967. foreach ($values as $field => $value) {
  968. $select[] = $field;
  969. if (is_array($value)) {
  970. // if the user has specified multiple values for matching then this we
  971. // want to catch that and save them in our $where array, otherwise
  972. // we'll descend for a foreign key relationship
  973. if (array_values($value) === $value) {
  974. $where[$field] = $value;
  975. }
  976. else {
  977. // select the value from the foreign key relationship for this value
  978. $foreign_options = array(
  979. 'regex_columns' => $options['regex_columns'],
  980. 'case_insensitive_columns' => $options['case_insensitive_columns']
  981. );
  982. if (array_key_exists('statement_name', $options) and $options['statement_name']) {
  983. // add the fk relationship info to the prepared statement name so that
  984. // we can prepare the selects run by the recrusive tripal_core_chado_get_foreign_key
  985. // function. we need the statement name to be unique so take the first two characters of each column
  986. $fk_sname = "fk_" . $table . "_" . $field;
  987. foreach ($value as $k => $v){
  988. $fk_sname .= substr($k, 0, 2);
  989. }
  990. $foreign_options['statement_name'] = $fk_sname;
  991. }
  992. $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value, $foreign_options);
  993. if (!$results or count($results)==0) {
  994. // foreign key records are required
  995. // thus if none matched then return FALSE and alert the admin through watchdog
  996. /*watchdog('tripal_core',
  997. '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',
  998. array('!table' => $table,
  999. '!columns' => '<pre>' . print_r($columns, TRUE) . '</pre>',
  1000. '!values' => '<pre>' . print_r($values, TRUE) . '</pre>',
  1001. '!field' => $field,
  1002. ),
  1003. WATCHDOG_WARNING);*/
  1004. return array();
  1005. }
  1006. else {
  1007. $where[$field] = $results;
  1008. }
  1009. }
  1010. }
  1011. else {
  1012. //need to catch a 0 and make int if integer field
  1013. if ($table_desc['fields'][$field]['type'] == 'int') {
  1014. $where[$field][] = (int) $value;
  1015. }
  1016. else {
  1017. $where[$field][] = $value;
  1018. }
  1019. }
  1020. }
  1021. // now build the SQL and prepared SQL statements. We may not use
  1022. // the prepared statement if it wasn't requested in the options of if the
  1023. // argument in a where statement has multiple values.
  1024. if (empty($where)) {
  1025. // sometimes want to select everything
  1026. $sql = "SELECT " . implode(', ', $columns) . " ";
  1027. $sql .= "FROM {$table} ";
  1028. // we don't prepare a statement if there is no where clause
  1029. $prepared = FALSE;
  1030. }
  1031. else {
  1032. $sql = "SELECT " . implode(', ', $columns) . " ";
  1033. $sql .= "FROM {$table} ";
  1034. $sql .= "WHERE ";
  1035. $psql = $sql; // prepared SQL statement;
  1036. $i = 1;
  1037. $pvalues = array();
  1038. $itypes = array();
  1039. foreach ($where as $field => $value) {
  1040. // if we have multiple values returned then we need an 'IN' statement
  1041. // in our where statement
  1042. if (count($value) > 1) {
  1043. $sql .= "$field IN (" . db_placeholders($value, 'varchar') . ") AND ";
  1044. foreach ($value as $v) {
  1045. $args[] = $v;
  1046. // we can't do a prepared statement with an 'IN' statement in a
  1047. // where clause because we can't guarantee we'll always have the
  1048. // same number of elements.
  1049. $prepared = FALSE;
  1050. }
  1051. }
  1052. // if we have a single value then we need an = in our where statement
  1053. else {
  1054. $operator = '=';
  1055. if (in_array($field, $options['regex_columns'])) {
  1056. $operator = '~*';
  1057. }
  1058. // get the types for the prepared statement. First check if the type
  1059. // is an integer
  1060. if (strcasecmp($table_desc['fields'][$field]['type'], 'serial')==0 OR
  1061. strcasecmp($table_desc['fields'][$field]['type'], 'int')==0 OR
  1062. strcasecmp($table_desc['fields'][$field]['type'], 'integer')==0) {
  1063. $sql .= "$field $operator %d AND ";
  1064. $psql .= "$field $operator \$" . $i . " AND ";
  1065. $args[] = $value[0];
  1066. // set the variables needed for the prepared statement
  1067. $idatatypes[] = 'int';
  1068. $itypes[] = '%d';
  1069. $pvalues[] = $value[0];
  1070. }
  1071. elseif (strcasecmp($table_desc['fields'][$field]['type'], 'boolean')==0) {
  1072. $sql .= "$field $operator %s AND ";
  1073. $psql .= "$field $operator \$" . $i . " AND ";
  1074. $args[] = $value[0];
  1075. // set the variables needed for the prepared statement
  1076. $idatatypes[] = 'bool';
  1077. $itypes[] = '%d';
  1078. $pvalues[] = $value[0];
  1079. }
  1080. elseif (strcasecmp($table_desc['fields'][$field]['type'], 'float')==0) {
  1081. $sql .= "$field $operator %s AND ";
  1082. $psql .= "$field $operator \$" . $i . " AND ";
  1083. $args[] = $value[0];
  1084. // set the variables needed for the prepared statement
  1085. $idatatypes[] = 'numeric';
  1086. $itypes[] = '%f';
  1087. $pvalues[] = $value[0];
  1088. }
  1089. // else the type is a text
  1090. else {
  1091. if (in_array($field, $options['case_insensitive_columns'])) {
  1092. $sql .= "lower($field) $operator lower('%s') AND ";
  1093. $psql .= "lower($field) $operator lower('\$" . $i . "') AND ";
  1094. $args[] = $value;
  1095. }
  1096. else {
  1097. $sql .= "$field $operator '%s' AND ";
  1098. $psql .= "$field $operator \$" . $i . " AND ";
  1099. $args[] = $value[0];
  1100. }
  1101. // set the variables needed for the prepared statement
  1102. $idatatypes[] = 'text';
  1103. $itypes[] = "'%s'";
  1104. $pvalues[] = $value[0];
  1105. }
  1106. }
  1107. $i++;
  1108. }
  1109. $sql = drupal_substr($sql, 0, -4); // get rid of the trailing 'AND '
  1110. $psql = drupal_substr($psql, 0, -4); // get rid of the trailing 'AND '
  1111. // finally add any ordering of the results to the SQL statement
  1112. if (count($options['order_by']) > 0) {
  1113. $sql .= " ORDER BY ";
  1114. $psql .= " ORDER BY ";
  1115. foreach ($options['order_by'] as $field => $dir) {
  1116. $sql .= "$field $dir, ";
  1117. $psql .= "$field $dir, ";
  1118. }
  1119. $sql = drupal_substr($sql, 0, -2); // get rid of the trailing ', '
  1120. $psql = drupal_substr($psql, 0, -2); // get rid of the trailing ', '
  1121. }
  1122. // finish constructing the prepared SQL statement
  1123. $psql = "PREPARE " . $options['statement_name'] . " (" . implode(', ', $idatatypes) . ") AS " . $psql;
  1124. } // end if(empty($where)){ } else {
  1125. // if the caller has requested the SQL rather than the results...
  1126. // which happens in the case of wanting to use the Drupal pager, then do so
  1127. if ($options['return_sql'] == TRUE) {
  1128. return array('sql' => $sql, 'args' => $args);
  1129. }
  1130. // prepare the statement
  1131. if ($prepared) {
  1132. // if this is the first time we've run this query
  1133. // then we need to do the prepare, otherwise just execute
  1134. if ($options['is_prepared'] != TRUE) {
  1135. $status = tripal_core_chado_prepare($options['statement_name'], $psql, $idatatypes);
  1136. if (!$status) {
  1137. return FALSE;
  1138. }
  1139. }
  1140. $sql = "EXECUTE " . $options['statement_name'] . "(" . implode(", ", $itypes) . ")";
  1141. // WARNING: This call creates a memory leak: if you remove the $pvalues it doesn't
  1142. // do this. Got to find out what's causing this.
  1143. $resource = tripal_core_chado_execute_prepared($options['statement_name'], $sql, $pvalues);
  1144. }
  1145. else {
  1146. $resource = chado_query($sql, $args);
  1147. }
  1148. // format results into an array
  1149. $results = array();
  1150. while ($r = db_fetch_object($resource)) {
  1151. $results[] = $r;
  1152. }
  1153. if ($options['has_record']) {
  1154. return count($results);
  1155. }
  1156. return $results;
  1157. }
  1158. /**
  1159. * Gets the value of a foreign key relationship
  1160. *
  1161. * This function is used by tripal_core_chado_select, tripal_core_chado_insert,
  1162. * and tripal_core_chado_update to iterate through the associate array of
  1163. * values that gets passed to each of those routines. The values array
  1164. * is nested where foreign key contraints are used to specify a value that. See
  1165. * documentation for any of those functions for further information.
  1166. *
  1167. * @param $table_desc
  1168. * A table description for the table with the foreign key relationship to be identified generated by
  1169. * hook_chado_<table name>_schema()
  1170. * @param $field
  1171. * The field in the table that is the foreign key.
  1172. * @param $values
  1173. * An associative array containing the values
  1174. * @param $options
  1175. * An associative array of additional options where the key is the option
  1176. * and the value is the value of that option. These options are passed on to tripal_core_chado_select.
  1177. *
  1178. * Additional Options Include:
  1179. * - case_insensitive_columns
  1180. * An array of columns to do a case insensitive search on.
  1181. * - regex_columns
  1182. * An array of columns where the value passed in should be treated as a regular expression
  1183. *
  1184. * @return
  1185. * A string containg the results of the foreign key lookup, or FALSE if failed.
  1186. *
  1187. * Example usage:
  1188. * @code
  1189. *
  1190. * $values = array(
  1191. * 'genus' => 'Citrus',
  1192. * 'species' => 'sinensis',
  1193. * );
  1194. * $value = tripal_core_chado_get_foreign_key('feature', 'organism_id',$values);
  1195. *
  1196. * @endcode
  1197. * The above code selects a record from the feature table using the three fields
  1198. * that uniquely identify a feature. The $columns array simply lists the columns
  1199. * to select. The $values array is nested such that the organism is identified by
  1200. * way of the organism_id foreign key constraint by specifying the genus and
  1201. * species. The cvterm is also specified using its foreign key and the cv_id
  1202. * for the cvterm is nested as well.
  1203. *
  1204. * @ingroup tripal_chado_api
  1205. */
  1206. function tripal_core_chado_get_foreign_key($table_desc, $field, $values, $options = NULL) {
  1207. // set defaults for options. If we don't set defaults then
  1208. // we get memory leaks when we try to access the elements
  1209. if (!is_array($options)) {
  1210. $options = array();
  1211. }
  1212. if (!array_key_exists('case_insensitive_columns', $options)) {
  1213. $options['case_insensitive_columns'] = array();
  1214. }
  1215. if (!array_key_exists('regex_columns', $options)) {
  1216. $options['regex_columns'] = array();
  1217. }
  1218. // get the list of foreign keys for this table description and
  1219. // iterate through those until we find the one we're looking for
  1220. $fkeys = '';
  1221. if (array_key_exists('foreign keys', $table_desc)) {
  1222. $fkeys = $table_desc['foreign keys'];
  1223. }
  1224. if ($fkeys) {
  1225. foreach ($fkeys as $name => $def) {
  1226. if (is_array($def['table'])) {
  1227. //foreign key was described 2X
  1228. $message = "The foreign key " . $name . " was defined twice. Please check modules "
  1229. ."to determine if hook_chado_schema_<version>_" . $table_desc['table'] . "() was "
  1230. ."implemented and defined this foreign key when it wasn't supposed to. Modules "
  1231. ."this hook was implemented in: " . implode(', ',
  1232. module_implements("chado_" . $table_desc['table'] . "_schema")) . ".";
  1233. watchdog('tripal_core', $message);
  1234. drupal_set_message(check_plain($message), 'error');
  1235. continue;
  1236. }
  1237. $table = $def['table'];
  1238. $columns = $def['columns'];
  1239. // iterate through the columns of the foreign key relationship
  1240. foreach ($columns as $left => $right) {
  1241. // does the left column in the relationship match our field?
  1242. if (strcmp($field, $left) == 0) {
  1243. // the column name of the foreign key matches the field we want
  1244. // so this is the right relationship. Now we want to select
  1245. $select_cols = array($right);
  1246. $result = tripal_core_chado_select($table, $select_cols, $values, $options);
  1247. $fields = array();
  1248. if ($result and count($result) > 0) {
  1249. foreach ($result as $obj) {
  1250. $fields[] = $obj->$right;
  1251. }
  1252. return $fields;
  1253. }
  1254. }
  1255. }
  1256. }
  1257. }
  1258. else {
  1259. // TODO: what do we do if we get to this point and we have a fk
  1260. // relationship expected but we don't have any definition for one in the
  1261. // table schema??
  1262. $version = tripal_core_get_chado_version(TRUE);
  1263. $message = t("There is no foreign key relationship defined for " . $field . ".
  1264. To define a foreign key relationship, determine the table this foreign
  1265. key referrs to (<foreign table>) and then implement
  1266. hook_chado_chado_schema_v<version>_<foreign table>(). See
  1267. tripal_feature_chado_v1_2_schema_feature for an example. Chado version: $version");
  1268. watchdog('tripal_core', $message);
  1269. drupal_set_message(check_plain($message), 'error');
  1270. }
  1271. return array();
  1272. }
  1273. /**
  1274. * Generates an object containing the full details of a record(s) in chado.
  1275. *
  1276. * This differs from the objects returned by tripal_core_chado_select in so far as all foreign key
  1277. * relationships have been followed meaning you have more complete details. Thus this function
  1278. * should be used whenever you need a full variable and tripal_core_chado_select should be used if
  1279. * you only case about a few columns.
  1280. *
  1281. * @param $table
  1282. * The name of the base table to generate a variable for
  1283. * @param $values
  1284. * A select values array that selects the records you want from the base table
  1285. * (this has the same form as tripal_core_chado_select)
  1286. * @param $base_options
  1287. * An array containing options for the base table. For example, an
  1288. * option of 'order_by' may be used to sort results in the base table
  1289. * if more than one are returned. The options must be compatible with
  1290. * the options accepted by the tripal_core_chado_select() function.
  1291. * @return
  1292. * Either an object (if only one record was selected from the base table)
  1293. * or an array of objects (if more than one record was selected from the base table).
  1294. *
  1295. * Example Usage:
  1296. * @code
  1297. $values = array(
  1298. 'name' => 'Medtr4g030710'
  1299. );
  1300. $features = tripal_core_generate_chado_var('feature', $values);
  1301. * @endcode
  1302. * This will return an object if there is only one feature with the name Medtr4g030710 or it will
  1303. * return an array of feature objects if more than one feature has that name.
  1304. *
  1305. * Note to Module Designers: Fields can be excluded by default from these objects by implementing
  1306. * one of the following hooks:
  1307. * - hook_exclude_field_from_tablename_by_default (where tablename is the name of the table):
  1308. * This hook allows you to add fields to be excluded on a per table basis. Simply implement
  1309. * this hook to return an array of fields to be excluded. For example:
  1310. * @code
  1311. mymodule_exclude_field_from_feature_by_default() {
  1312. return array('residues' => TRUE);
  1313. }
  1314. * @endcode
  1315. * will ensure that feature.residues is ecluded from a feature object by default.
  1316. * - hook_exclude_type_by_default:
  1317. * This hook allows you to exclude fields from all tables that are of a given postgresql field
  1318. * type. Simply implement this hook to return an array of postgresql types mapped to criteria.
  1319. * Then all fields of that type where the criteria supplied returns TRUE will be excluded from
  1320. * any table. Tokens available in criteria are &gt;field_value&lt; and &gt;field_name&lt; . For example:
  1321. * @code
  1322. mymodule_exclude_type_by_default() {
  1323. return array('text' => 'length(&gt;field_value&lt; ) > 50');
  1324. }
  1325. * @endcode
  1326. * 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.
  1327. *
  1328. * @ingroup tripal_chado_api
  1329. */
  1330. function tripal_core_generate_chado_var($table, $values, $base_options = array()) {
  1331. $all = new stdClass();
  1332. // get description for the current table----------------------------------------------------------
  1333. $table_desc = tripal_core_get_chado_table_schema($table);
  1334. $table_primary_key = $table_desc['primary key'][0];
  1335. $table_columns = array_keys($table_desc['fields']);
  1336. // Expandable fields without value needed for criteria--------------------------------------------
  1337. $all->expandable_fields = array();
  1338. if ($table_desc['referring_tables']) {
  1339. $all->expandable_tables = $table_desc['referring_tables'];
  1340. }
  1341. else {
  1342. $all->expandable_tables = array();
  1343. }
  1344. $all->expandable_nodes = array();
  1345. // Get fields to be removed by name.................................
  1346. $fields_to_remove = module_invoke_all('exclude_field_from_' . $table . '_by_default');
  1347. foreach ($fields_to_remove as $field_name => $criteria) {
  1348. //replace &gt;field_name&lt; with the current field name &
  1349. $criteria = preg_replace('/&gt;field_name&lt; /', $field_name, $criteria);
  1350. // if field_value needed we can't deal with this field yet
  1351. if (preg_match('/&gt;field_value&lt; /', $criteria)) {
  1352. break;
  1353. }
  1354. //if criteria then remove from query
  1355. // @coder-ignore: only module designers can populate $criteria -not security risk
  1356. $success = drupal_eval('<?php return ' . $criteria . '; ?>');
  1357. // watchdog('tripal_core',
  1358. // 'Evaluating criteria (%criteria) for field %field in tripal_core_generate_chado_var for %table evaluated to %success',
  1359. // array('%table' => $table, '%criteria'=>$criteria, '%field' => $field_name, '%success'=>$success),
  1360. // WATCHDOG_NOTICE
  1361. // );
  1362. if ($success) {
  1363. unset($table_columns[array_search($field_name, $table_columns)]);
  1364. unset($fields_to_remove[$field_name]);
  1365. $all->expandable_fields[] = $table . '.' . $field_name;
  1366. }
  1367. }
  1368. //Get fields to be removed by type................................
  1369. $types_to_remove = module_invoke_all('exclude_type_by_default');
  1370. $field_types = array();
  1371. foreach ($table_desc['fields'] as $field_name => $field_array) {
  1372. $field_types[$field_array['type']][] = $field_name;
  1373. }
  1374. foreach ($types_to_remove as $field_type => $criteria) {
  1375. // if there are fields of that type to remove
  1376. if (is_array($field_types[$field_type])) {
  1377. //replace &gt;field_name&lt; with the current field name &
  1378. $criteria = preg_replace('/&gt;field_name&lt; /', $field_name, $criteria);
  1379. foreach ($field_types[$field_type] as $field_name) {
  1380. // if field_value needed we can't deal with this field yet
  1381. if (preg_match('/&gt;field_value&lt; /', $criteria)) {
  1382. $fields_to_remove[$field_name] = $criteria;
  1383. continue;
  1384. }
  1385. // if field_value needed we can't deal with this field yet
  1386. if (preg_match('/&gt;field_value&lt; /', $criteria)) {
  1387. break;
  1388. }
  1389. //if criteria then remove from query
  1390. // @coder-ignore: only module designers can populate $criteria -not security risk
  1391. $success = drupal_eval('<?php return ' . $criteria . '; ?>');
  1392. // watchdog('tripal_core',
  1393. // 'Evaluating criteria (%criteria) for field %field of $type in tripal_core_generate_chado_var for %table evaluated to %success',
  1394. // array('%table'=>$table, '%criteria'=>$criteria, '%field'=>$field_name, '%type'=>$field_type, '%success'=>$success),
  1395. // WATCHDOG_NOTICE
  1396. // );
  1397. if ($success) {
  1398. unset($table_columns[array_search($field_name, $table_columns)]);
  1399. $all->expandable_fields[] = $table . '.' . $field_name;
  1400. }
  1401. } //end of foreach field of that type
  1402. }
  1403. } //end of foreach type to be removed
  1404. // get the values for the record in the current table---------------------------------------------
  1405. $results = tripal_core_chado_select($table, $table_columns, $values, $base_options);
  1406. if ($results) {
  1407. foreach ($results as $key => $object) {
  1408. // Add empty expandable_x arrays
  1409. $object->expandable_fields = $all->expandable_fields;
  1410. $object->expandable_tables = $all->expandable_tables;
  1411. $object->expandable_nodes = $all->expandable_nodes;
  1412. // add curent table
  1413. $object->tablename = $table;
  1414. // check if the current table maps to a node type-----------------------------------------------
  1415. // if this table is connected to a node there will be a chado_tablename table in drupal
  1416. if (db_table_exists('chado_' . $table)) {
  1417. // that has a foreign key to this one ($table_desc['primary key'][0]
  1418. // and to the node table (nid)
  1419. $sql = "SELECT %s, nid FROM {chado_%s} WHERE %s=%d";
  1420. $mapping = db_fetch_object(db_query(
  1421. $sql,
  1422. $table_primary_key,
  1423. $table,
  1424. $table_primary_key,
  1425. $object->{$table_primary_key}
  1426. ));
  1427. if ($mapping->{$table_primary_key}) {
  1428. $object->nid = $mapping->nid;
  1429. $object->expandable_nodes[] = $table;
  1430. }
  1431. }
  1432. // remove any fields where criteria need to be evalulated---------------------------------------
  1433. foreach ($fields_to_remove as $field_name => $criteria) {
  1434. if (!isset($object->{$field_name})) {
  1435. break;
  1436. }
  1437. $criteria = preg_replace('/&gt;field_value&lt; /', $object->{$field_name}, $criteria);
  1438. //if criteria then remove from query
  1439. // @coder-ignore: only module designers can populate $criteria -not security risk
  1440. $success = drupal_eval('<?php return ' . $criteria . '; ?>');
  1441. // watchdog('tripal_core',
  1442. // 'Evaluating criteria (%criteria) for field %field in tripal_core_generate_chado_var for %table evaluated to %success',
  1443. // array('%table' => $table, '%criteria'=>$criteria, '%field' => $field_name, '%success'=>$success),
  1444. // WATCHDOG_NOTICE
  1445. // );
  1446. if ($success) {
  1447. unset($object->{$field_name});
  1448. $object->expandable_fields[] = $table . '.' . $field_name;
  1449. }
  1450. }
  1451. // recursively follow foreign key relationships nesting objects as we go------------------------
  1452. if ($table_desc['foreign keys']) {
  1453. foreach ($table_desc['foreign keys'] as $foreign_key_array) {
  1454. $foreign_table = $foreign_key_array['table'];
  1455. foreach ($foreign_key_array['columns'] as $foreign_key => $primary_key) {
  1456. // Note: Foreign key is the field in the current table whereas primary_key is the field in
  1457. // the table referenced by the foreign key
  1458. //Dont do anything if the foreign key is empty
  1459. if (empty($object->{$foreign_key})) {
  1460. break;
  1461. }
  1462. // get the record from the foreign table
  1463. $foreign_values = array($primary_key => $object->{$foreign_key});
  1464. $foreign_object = tripal_core_generate_chado_var($foreign_table, $foreign_values);
  1465. // add the foreign record to the current object in a nested manner
  1466. $object->{$foreign_key} = $foreign_object;
  1467. // Flatten expandable_x arrays so only in the bottom object
  1468. if (is_array($object->{$foreign_key}->expandable_fields)) {
  1469. $object->expandable_fields = array_merge(
  1470. $object->expandable_fields,
  1471. $object->{$foreign_key}->expandable_fields
  1472. );
  1473. unset($object->{$foreign_key}->expandable_fields);
  1474. }
  1475. if (is_array($object->{$foreign_key}->expandable_tables)) {
  1476. $object->expandable_tables = array_merge(
  1477. $object->expandable_tables,
  1478. $object->{$foreign_key}->expandable_tables
  1479. );
  1480. unset($object->{$foreign_key}->expandable_tables);
  1481. }
  1482. if (is_array($object->{$foreign_key}->expandable_nodes)) {
  1483. $object->expandable_nodes = array_merge(
  1484. $object->expandable_nodes,
  1485. $object->{$foreign_key}->expandable_nodes
  1486. );
  1487. unset($object->{$foreign_key}->expandable_nodes);
  1488. }
  1489. }
  1490. }
  1491. $results[$key] = $object;
  1492. }
  1493. }
  1494. }
  1495. // check only one result returned
  1496. if (sizeof($results) == 1) {
  1497. // add results to object
  1498. return $results[0];
  1499. }
  1500. elseif (!empty($results)) {
  1501. return $results;
  1502. }
  1503. else {
  1504. // no results returned
  1505. }
  1506. }
  1507. /**
  1508. * Retrieves fields/tables/nodes that were excluded by default from a variable and adds them
  1509. *
  1510. * This function exists to allow tripal_core_generate_chado_var() to excldue some
  1511. * fields/tables/nodes from the default form of a variable without making it extremely difficult for
  1512. * the tripal admin to get at these variables if he/she wants them.
  1513. *
  1514. * @param $object
  1515. * This must be an object generated using tripal_core_generate_chado_var()
  1516. * @param $type
  1517. * Must be one of 'field', 'table', 'node'. Indicates what is being expanded.
  1518. * @param $to_expand
  1519. * The name of the field/table/node to be expanded
  1520. * @param $table_options
  1521. * An array containing options for the base table. For example, an
  1522. * option of 'order_by' may be used to sort results in the base table
  1523. * if more than one are returned. The options must be compatible with
  1524. * the options accepted by the tripal_core_chado_select() function.
  1525. * @return
  1526. * A chado object supplemented with the field/table/node requested to be expanded
  1527. *
  1528. * Example Usage:
  1529. * @code
  1530. // Get a chado object to be expanded
  1531. $values = array(
  1532. 'name' => 'Medtr4g030710'
  1533. );
  1534. $features = tripal_core_generate_chado_var('feature', $values);
  1535. // Expand the organism node
  1536. $feature = tripal_core_expand_chado_vars($feature, 'node', 'organism');
  1537. // Expand the feature.residues field
  1538. $feature = tripal_core_expand_chado_vars($feature, 'field', 'feature.residues');
  1539. // Expand the feature properties (featureprop table)
  1540. $feature = tripal_core_expand_chado_vars($feature, 'table', 'featureprop');
  1541. * @endcode
  1542. *
  1543. * @ingroup tripal_chado_api
  1544. */
  1545. function tripal_core_expand_chado_vars($object, $type, $to_expand, $table_options = array()) {
  1546. $base_table = $object->tablename;
  1547. // check to see if they are expanding an array of objects
  1548. if (is_array($object)) {
  1549. foreach ($object as $index => $o) {
  1550. $object[$index] = tripal_core_expand_chado_vars($o, $type, $to_expand);
  1551. }
  1552. return $object;
  1553. }
  1554. switch ($type) {
  1555. case "field": //--------------------------------------------------------------------------------
  1556. if (preg_match('/(\w+)\.(\w+)/', $to_expand, $matches)) {
  1557. $tablename = $matches[1];
  1558. $fieldname = $matches[2];
  1559. $table_desc = tripal_core_get_chado_table_schema($tablename);
  1560. $values = array();
  1561. foreach ($table_desc['primary key'] as $key) {
  1562. $values[$key] = $object->{$key};
  1563. }
  1564. if ($base_table == $tablename) {
  1565. //get the field
  1566. $results = tripal_core_chado_select(
  1567. $tablename,
  1568. array($fieldname),
  1569. $values
  1570. );
  1571. $object->{$fieldname} = $results[0]->{$fieldname};
  1572. $object->expanded = $to_expand;
  1573. }
  1574. else {
  1575. //We need to recurse -the field is in a nested object
  1576. foreach ((array) $object as $field_name => $field_value) {
  1577. if (is_object($field_value)) {
  1578. $object->{$field_name} = tripal_core_expand_chado_vars(
  1579. $field_value,
  1580. 'field',
  1581. $to_expand
  1582. );
  1583. }
  1584. } //end of for each field in the current object
  1585. }
  1586. }
  1587. else {
  1588. watchdog(
  1589. 'tripal_core',
  1590. 'tripal_core_expand_chado_vars: Field (%field) not in the right format. It should be <tablename>.<fieldname>',
  1591. WATCHDOG_ERROR
  1592. );
  1593. }
  1594. break;
  1595. case "table": //--------------------------------------------------------------------------------
  1596. $foreign_table = $to_expand;
  1597. $foreign_table_desc = tripal_core_get_chado_table_schema($foreign_table);
  1598. // If it's connected to the base table
  1599. if ($foreign_table_desc['foreign keys'][$base_table]) {
  1600. foreach ($foreign_table_desc['foreign keys'][$base_table]['columns'] as $left => $right) {
  1601. if (!$object->{$right}) {
  1602. break;
  1603. }
  1604. if (is_array($values)) {
  1605. $values = array_merge($values, array($left => $object->{$right}) );
  1606. }
  1607. else {
  1608. $values = array($left => $object->{$right});
  1609. }
  1610. $foreign_object = tripal_core_generate_chado_var(
  1611. $foreign_table,
  1612. array($left => $object->{$right}),
  1613. $table_options
  1614. );
  1615. if ($foreign_object) {
  1616. // in the case where the foreign key relationships exists more
  1617. // than once with the same table we want to alter the
  1618. // array structure
  1619. if (count($foreign_table_desc['foreign keys'][$base_table]['columns']) > 1) {
  1620. if (!is_object($object->{$foreign_table})) {
  1621. $object->{$foreign_table} = new stdClass();
  1622. }
  1623. $object->{$foreign_table}->{$left} = $foreign_object;
  1624. $object->expanded = $to_expand;
  1625. }
  1626. else {
  1627. $object->{$foreign_table} = $foreign_object;
  1628. $object->expanded = $to_expand;
  1629. }
  1630. }
  1631. }
  1632. }
  1633. else {
  1634. //We need to recurse -the table has a relationship to one of the nested objects
  1635. foreach ((array) $object as $field_name => $field_value) {
  1636. // if we have a nested object ->expand the table in it
  1637. if (is_object($field_value)) {
  1638. $object->{$field_name} = tripal_core_expand_chado_vars(
  1639. $field_value,
  1640. 'table',
  1641. $foreign_table
  1642. );
  1643. }
  1644. }
  1645. }
  1646. break;
  1647. case "node": //---------------------------------------------------------------------------------
  1648. //if the node to be expanded is for our base table, then just expand it
  1649. if ($object->tablename == $to_expand) {
  1650. $node = node_load($object->nid);
  1651. if ($node) {
  1652. $object->expanded = $to_expand;
  1653. $node->expandable_fields = $object->expandable_fields;
  1654. unset($object->expandable_fields);
  1655. $node->expandable_tables = $object->expandable_tables;
  1656. unset($object->expandable_tables);
  1657. $node->expandable_nodes = $object->expandable_nodes;
  1658. unset($object->expandable_nodes);
  1659. $node->{$base_table} = $object;
  1660. $object = $node;
  1661. }
  1662. else {
  1663. watchdog(
  1664. 'tripal_core',
  1665. 'tripal_core_expand_chado_vars: No node matches the nid (%nid) supplied.',
  1666. array('%nid' => $object->nid),
  1667. WATCHDOG_ERROR
  1668. );
  1669. } //end of if node
  1670. }
  1671. else {
  1672. //We need to recurse -the node to expand is one of the nested objects
  1673. foreach ((array) $object as $field_name => $field_value) {
  1674. if (is_object($field_value)) {
  1675. $object->{$field_name} = tripal_core_expand_chado_vars(
  1676. $field_value,
  1677. 'node',
  1678. $to_expand
  1679. );
  1680. }
  1681. } //end of for each field in the current object
  1682. }
  1683. break;
  1684. default:
  1685. watchdog('tripal_core',
  1686. 'tripal_core_expand_chado_vars: Unrecognized type (%type). Should be one of "field", "table", "node".',
  1687. array('%type' => $type),
  1688. WATCHDOG_ERROR
  1689. );
  1690. return FALSE;
  1691. }
  1692. //move extended array downwards-------------------------------------------------------------------
  1693. if (!$object->expanded) {
  1694. //if there's no extended field then go hunting for it
  1695. foreach ( (array)$object as $field_name => $field_value) {
  1696. if (is_object($field_value)) {
  1697. if (isset($field_value->expanded)) {
  1698. $object->expanded = $field_value->expanded;
  1699. unset($field_value->expanded);
  1700. }
  1701. }
  1702. }
  1703. }
  1704. //try again becasue now we might have moved it down
  1705. if ($object->expanded) {
  1706. $expandable_name = 'expandable_' . $type . 's';
  1707. if ($object->{$expandable_name}) {
  1708. $key_to_remove = array_search($object->expanded, $object->{$expandable_name});
  1709. unset($object->{$expandable_name}[$key_to_remove]);
  1710. unset($object->expanded);
  1711. }
  1712. else {
  1713. // if there is an expandable array then we've reached the base object
  1714. // if we get here and don't have anything expanded then something went wrong
  1715. // watchdog(
  1716. // 'tripal_core',
  1717. // 'tripal_core_expand_chado_vars: Unable to expand the %type %to_expand',
  1718. // array('%type'=>$type, '%to_expand'=>$to_expand),
  1719. // WATCHDOG_ERROR
  1720. // );
  1721. } //end of it we've reached the base object
  1722. }
  1723. return $object;
  1724. }
  1725. /**
  1726. * Implements hook_exclude_type_by_default()
  1727. *
  1728. * This hooks allows fields of a specified type that match a specified criteria to be excluded by
  1729. * default from any table when tripal_core_generate_chado_var() is called. Keep in mind that if
  1730. * fields are excluded by default they can always be expanded at a later date using
  1731. * tripal_core_expand_chado_vars().
  1732. *
  1733. * Criteria are php strings that evaluate to either TRUE or FALSE. These strings are evaluated using
  1734. * drupal_eval() which suppresses syntax errors and throws watchdog entries of type php. There are
  1735. * also watchdog entries of type tripal_core stating the exact criteria evaluated. Criteria can
  1736. * contain the following tokens:
  1737. * - &gt;field_name&lt;
  1738. * Replaced by the name of the field to be excluded
  1739. * - &gt;field_value&lt;
  1740. * Replaced by the value of the field in the current record
  1741. * Also keep in mind that if your criteria doesn't contain the &gt;field_value&lt; token then it will be
  1742. * evaluated before the query is executed and if the field is excluded it won't be included in the
  1743. * query.
  1744. *
  1745. * @return
  1746. * An array of type => criteria where the type is excluded if the criteria evaluates to TRUE
  1747. *
  1748. * @ingroup tripal_chado_api
  1749. */
  1750. function tripal_core_exclude_type_by_default() {
  1751. return array('text' => "strlen('&gt;field_value&lt; ') > 100");
  1752. }
  1753. /**
  1754. * Implements hook_exclude_field_from_<tablename>_by_default()
  1755. *
  1756. * This hooks allows fields from a specified table that match a specified criteria to be excluded by
  1757. * default from any table when tripal_core_generate_chado_var() is called. Keep in mind that if
  1758. * fields are excluded by default they can always be expanded at a later date using
  1759. * tripal_core_expand_chado_vars().
  1760. *
  1761. * Criteria are php strings that evaluate to either TRUE or FALSE. These strings are evaluated using
  1762. * drupal_eval() which suppresses syntax errors and throws watchdog entries of type php. There are
  1763. * also watchdog entries of type tripal_core stating the exact criteria evaluated. Criteria can
  1764. * contain the following tokens:
  1765. * - &gt;field_name&lt;
  1766. * Replaced by the name of the field to be excluded
  1767. * - &gt;field_value&lt;
  1768. * Replaced by the value of the field in the current record
  1769. * Also keep in mind that if your criteria doesn't contain the &gt;field_value&lt; token then it will be
  1770. * evaluated before the query is executed and if the field is excluded it won't be included in the
  1771. * query.
  1772. *
  1773. * @return
  1774. * An array of type => criteria where the type is excluded if the criteria evaluates to TRUE
  1775. *
  1776. * @ingroup tripal_chado_api
  1777. */
  1778. function tripal_core_exclude_field_from_feature_by_default() {
  1779. return array();
  1780. }
  1781. /**
  1782. * Use this function instead of db_query() to avoid switching databases
  1783. * when making query to the chado database
  1784. *
  1785. * Will use a chado persistent connection if it already exists
  1786. *
  1787. * @param $sql
  1788. * The sql statement to execute
  1789. *
  1790. * @returns
  1791. * A database query result resource or FALSE if the query was not
  1792. * executed correctly
  1793. */
  1794. function chado_query($sql) {
  1795. //print memory_get_usage() . "\n";
  1796. $args = func_get_args();
  1797. array_shift($args); // remove the $sql from the argument list
  1798. $sql = db_prefix_tables($sql);
  1799. if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
  1800. $args = $args[0];
  1801. }
  1802. _db_query_callback($args, TRUE);
  1803. $sql = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $sql);
  1804. // Execute the query on the chado database/schema
  1805. // Use the persistent chado connection if it already exists
  1806. $persistent_connection = unserialize(variable_get('tripal_persistent_chado', NULL));
  1807. if ($persistent_connection) {
  1808. $query = $sql;
  1809. // Duplicate the _db_query code in order to ensure that the drupal
  1810. // $active_db variable is never touched
  1811. // thus changed $active_db to $persistent_connection
  1812. // START COPY FROM _db_query in database.pgsql.inc
  1813. if (variable_get('dev_query', 0)) {
  1814. list($usec, $sec) = explode(' ', microtime());
  1815. $timer = (float) $usec + (float) $sec;
  1816. }
  1817. $last_result = pg_query($persistent_connection, $query);
  1818. if (variable_get('dev_query', 0)) {
  1819. $bt = debug_backtrace();
  1820. $query = $bt[2]['function'] . "\n" . $query;
  1821. list($usec, $sec) = explode(' ', microtime());
  1822. $stop = (float) $usec + (float) $sec;
  1823. $diff = $stop - $timer;
  1824. $queries[] = array($query, $diff);
  1825. }
  1826. if ($debug) {
  1827. print '<p>query: ' . $query . '<br />error:' . pg_last_error($persistent_connection) . '</p>';
  1828. }
  1829. if ($last_result !== FALSE) {
  1830. return $last_result;
  1831. }
  1832. else {
  1833. // Indicate to drupal_error_handler that this is a database error.
  1834. ${DB_ERROR} = TRUE;
  1835. trigger_error(check_plain(pg_last_error($persistent_connection) . "\nquery: " . $query), E_USER_WARNING);
  1836. return FALSE;
  1837. }
  1838. // END COPY FROM _db_query in database.pgsql.inc
  1839. }
  1840. else {
  1841. $previous_db = tripal_db_set_active('chado');
  1842. $results = _db_query($sql);
  1843. tripal_db_set_active($previous_db);
  1844. }
  1845. return $results;
  1846. }
  1847. /**
  1848. * Get chado id for a node. E.g, if you want to get 'analysis_id' from the
  1849. * 'analysis' table for a synced 'chado_analysis' node, use:
  1850. * $analysis_id = chado_get_id_for_node ('analysis', $node)
  1851. * Likewise,
  1852. * $organism_id = chado_get_id_for_node ('organism', $node)
  1853. * $feature_id = chado_get_id_for_node ('feature', $node)
  1854. */
  1855. function chado_get_id_for_node($table, $node) {
  1856. return db_result(db_query("SELECT %s_id FROM {chado_%s} WHERE nid = %d", $table, $table, $node->nid));
  1857. }
  1858. /**
  1859. * Get node id for a chado feature/organism/analysis. E.g, if you want to
  1860. * get the node id for an analysis, use:
  1861. * $nid = chado_get_node_id ('analysis', $analysis_id)
  1862. * Likewise,
  1863. * $nid = chado_get_node_id ('organism', $organism_id)
  1864. * $nid = chado_get_node_id ('feature', $feature_id)
  1865. */
  1866. function chado_get_node_id($table, $id) {
  1867. return db_result(db_query("SELECT nid FROM {chado_%s} WHERE %s_id = %d", $table, $table, $id));
  1868. }
  1869. /**
  1870. * Retrieve a property for a given base table record
  1871. *
  1872. * @param $basetable
  1873. * The base table for which the property should be retrieved. Thus to retrieve a property
  1874. * for a feature the basetable=feature and property is retrieved from featureprop
  1875. * @param $record_id
  1876. * The foriegn key field of the base table. This should be in integer.
  1877. * @param $property
  1878. * The cvterm name describing the type of properties to be retrieved
  1879. * @param $cv_name
  1880. * The name of the cv that the above cvterm is part of
  1881. *
  1882. * @return
  1883. * An array in the same format as that generated by the function
  1884. * tripal_core_generate_chado_var(). If only one record is returned it
  1885. * is a single object. If more than one record is returned then it is an array
  1886. * of objects
  1887. *
  1888. * @ingroup tripal_chado_api
  1889. */
  1890. function tripal_core_get_property($basetable, $record_id, $property, $cv_name) {
  1891. // get the foreign key for this property table
  1892. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  1893. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1894. // construct the array of values to be selected
  1895. $values = array(
  1896. $fkcol => $record_id,
  1897. 'type_id' => array(
  1898. 'cv_id' => array(
  1899. 'name' => $cv_name,
  1900. ),
  1901. 'name' => $property,
  1902. 'is_obsolete' => 0
  1903. ),
  1904. );
  1905. $results = tripal_core_generate_chado_var($basetable . 'prop', $values);
  1906. $results = tripal_core_expand_chado_vars($results, 'field', $basetable . 'prop.value');
  1907. return $results;
  1908. }
  1909. /**
  1910. * Insert a property for a given base table. By default if the property already
  1911. * exists a new property is added with the next available rank. If
  1912. * $update_if_present argument is specified then the record will be updated if it
  1913. * exists rather than adding a new property.
  1914. *
  1915. * @param $basetable
  1916. * The base table for which the property should be inserted. Thus to insert a property
  1917. * for a feature the basetable=feature and property is inserted into featureprop
  1918. * @param $record_id
  1919. * The foriegn key field of the base table. This should be in integer.
  1920. * @param $property
  1921. * The cvterm name describing the type of properties to be inserted
  1922. * @param $cv_name
  1923. * The name of the cv that the above cvterm is part of
  1924. * @param $value
  1925. * The value of the property to be inserted (can be empty)
  1926. * @param $update_if_present
  1927. * A boolean indicating whether an existing record should be updated. If the
  1928. * property already exists and this value is not specified or is zero then
  1929. * a new property will be added with the next largest rank.
  1930. *
  1931. * @return
  1932. * Return True on Insert/Update and False otherwise
  1933. *
  1934. * @ingroup tripal_chado_api
  1935. */
  1936. function tripal_core_insert_property($basetable, $record_id, $property,
  1937. $cv_name, $value, $update_if_present = 0) {
  1938. // first see if the property already exists, if the user want's to update
  1939. // then we can do that, but otherwise we want to increment the rank and
  1940. // insert
  1941. $props = tripal_core_get_property($basetable, $record_id, $property, $cv_name);
  1942. if (!is_array($props)) {
  1943. $props = array($props);
  1944. }
  1945. $rank = 0;
  1946. if (count($props) > 0) {
  1947. if ($update_if_present) {
  1948. return tripal_core_update_property($basetable, $record_id, $property, $cv_name, $value);
  1949. }
  1950. else {
  1951. // iterate through the properties returned and check to see if the
  1952. // property with this value already exists if not, get the largest rank
  1953. // and insert the same property but with this new value
  1954. foreach ($props as $p) {
  1955. if ($p->rank > $rank) {
  1956. $rank = $p->rank;
  1957. }
  1958. if (strcmp($p->value, $value) == 0) {
  1959. return TRUE;
  1960. }
  1961. }
  1962. // now add 1 to the rank
  1963. $rank++;
  1964. }
  1965. }
  1966. else {
  1967. watchdog('tripal_core', "Cannot find property '!prop_name'.",
  1968. array('!prop_name' => $property), WATCHDOG_ERROR);
  1969. }
  1970. // get the foreign key for this property table
  1971. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  1972. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1973. // construct the array of values to be inserted
  1974. $values = array(
  1975. $fkcol => $record_id,
  1976. 'type_id' => array(
  1977. 'cv_id' => array(
  1978. 'name' => $cv_name,
  1979. ),
  1980. 'name' => $property,
  1981. 'is_obsolete' => 0
  1982. ),
  1983. 'value' => $value,
  1984. 'rank' => $rank,
  1985. );
  1986. return tripal_core_chado_insert($basetable . 'prop', $values);
  1987. }
  1988. /**
  1989. * Update a property for a given base table record and property name. This
  1990. * function should be used only if one record of the property will be present.
  1991. * If the property name can have multiple entries (with increasing rank) then
  1992. * use the function named tripal_core_update_property_by_id
  1993. *
  1994. * @param $basetable
  1995. * The base table for which the property should be updated. The property table
  1996. * is constructed using a combination of the base table name and the suffix
  1997. * 'prop' (e.g. basetable = feature then property tabie is featureprop).
  1998. * @param $record_id
  1999. * The foreign key of the basetable to update a property for. This should be in integer.
  2000. * For example, if the basetable is 'feature' then the $record_id should be the feature_id
  2001. * @param $property
  2002. * The cvterm name of property to be updated
  2003. * @param $cv_name
  2004. * The name of the cv that the above cvterm is part of
  2005. * @param $value
  2006. * The value of the property to be inserted (can be empty)
  2007. * @param $insert_if_missing
  2008. * A boolean indicating whether a record should be inserted if one doesn't exist to update
  2009. *
  2010. * Note: The property to be updated is select via the unique combination of $record_id and
  2011. * $property and then it is updated with the supplied value
  2012. *
  2013. * @return
  2014. * Return True on Update/Insert and False otherwise
  2015. *
  2016. * @ingroup tripal_chado_api
  2017. */
  2018. function tripal_core_update_property($basetable, $record_id, $property,
  2019. $cv_name, $value, $insert_if_missing = 0) {
  2020. // first see if the property is missing (we can't update a missing property
  2021. $prop = tripal_core_get_property($basetable, $record_id, $property, $cv_name);
  2022. if (count($prop)==0) {
  2023. if ($insert_if_missing) {
  2024. return tripal_core_insert_property($basetable, $record_id, $property, $cv_name, $value);
  2025. }
  2026. else {
  2027. return FALSE;
  2028. }
  2029. }
  2030. // get the foreign key for this property table
  2031. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  2032. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  2033. // construct the array that will match the exact record to update
  2034. $match = array(
  2035. $fkcol => $record_id,
  2036. 'type_id' => array(
  2037. 'cv_id' => array(
  2038. 'name' => $cv_name,
  2039. ),
  2040. 'name' => $property,
  2041. ),
  2042. );
  2043. // construct the array of values to be updated
  2044. $values = array(
  2045. 'value' => $value,
  2046. );
  2047. return tripal_core_chado_update($basetable . 'prop', $match, $values);
  2048. }
  2049. /**
  2050. * Update a property for a given base table record. This function should be
  2051. * used if multiple records of the same property will be present. Also, use this
  2052. * function to change the property name of an existing property.
  2053. *
  2054. * @param $basetable
  2055. * The base table for which the property should be updated. The property table
  2056. * is constructed using a combination of the base table name and the suffix
  2057. * 'prop' (e.g. basetable = feature then property tabie is featureprop).
  2058. * @param $record_id
  2059. * The primary key of the base table. This should be in integer.
  2060. * For example, if the basetable is 'feature' then the $record_id should be the featureprop_id
  2061. * @param $property
  2062. * The cvterm name of property to be updated
  2063. * @param $cv_name
  2064. * The name of the cv that the above cvterm is part of
  2065. * @param $value
  2066. * The value of the property to be inserted (can be empty)
  2067. *
  2068. * @return
  2069. * Return True on Update/Insert and False otherwise
  2070. *
  2071. * @ingroup tripal_chado_api
  2072. */
  2073. function tripal_core_update_property_by_id($basetable, $record_id, $property,
  2074. $cv_name, $value) {
  2075. // get the primary key for this property table
  2076. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  2077. $pkcol = $table_desc['primary key'][0];
  2078. // construct the array that will match the exact record to update
  2079. $match = array(
  2080. $pkcol => $record_id,
  2081. );
  2082. // construct the array of values to be updated
  2083. $values = array(
  2084. 'type_id' => array(
  2085. 'cv_id' => array(
  2086. 'name' => $cv_name,
  2087. ),
  2088. 'name' => $property,
  2089. ),
  2090. 'value' => $value,
  2091. );
  2092. return tripal_core_chado_update($basetable . 'prop', $match, $values);
  2093. }
  2094. /**
  2095. * Deletes a property for a given base table record using the property name
  2096. *
  2097. * @param $basetable
  2098. * The base table for which the property should be deleted. Thus to deleted a property
  2099. * for a feature the basetable=feature and property is deleted from featureprop
  2100. * @param $record_id
  2101. * The primary key of the basetable to delete a property for. This should be in integer.
  2102. * @param $property
  2103. * The cvterm name describing the type of property to be deleted
  2104. * @param $cv_name
  2105. * The name of the cv that the above cvterm is part of
  2106. *
  2107. * Note: The property to be deleted is select via the unique combination of $record_id and $property
  2108. *
  2109. * @return
  2110. * Return True on Delete and False otherwise
  2111. *
  2112. * @ingroup tripal_chado_api
  2113. */
  2114. function tripal_core_delete_property($basetable, $record_id, $property, $cv_name) {
  2115. // get the foreign key for this property table
  2116. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  2117. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  2118. // construct the array that will match the exact record to update
  2119. $match = array(
  2120. $fkcol => $record_id,
  2121. 'type_id' => array(
  2122. 'cv_id' => array(
  2123. 'name' => $cv_name,
  2124. ),
  2125. 'name' => $property,
  2126. ),
  2127. );
  2128. return tripal_core_chado_delete($basetable . 'prop', $match);
  2129. }
  2130. /**
  2131. * Deletes a property using the property ID
  2132. *
  2133. * @param $basetable
  2134. * The base table for which the property should be deleted. Thus to deleted a property
  2135. * for a feature the basetable=feature and property is deleted from featureprop
  2136. * @param $record_id
  2137. * The primary key of the basetable to delete a property for. This should be in integer.
  2138. *
  2139. * @return
  2140. * Return True on Delete and False otherwise
  2141. *
  2142. * @ingroup tripal_chado_api
  2143. */
  2144. function tripal_core_delete_property_by_id($basetable, $record_id) {
  2145. // get the foreign key for this property table
  2146. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  2147. $pkcol = $table_desc['primary key'][0];
  2148. // construct the array that will match the exact record to update
  2149. $match = array(
  2150. $pkcol => $record_id,
  2151. );
  2152. return tripal_core_chado_delete($basetable . 'prop', $match);
  2153. }
  2154. /**
  2155. * This function is typically used in the '.install' file for a Tripal module
  2156. * Each module should call this function during installation to create
  2157. * the module data directory which is sites/default/files/tripal/[module_name]
  2158. * for default Drupal settings. This directory can then be used by the module
  2159. * for storing files.
  2160. *
  2161. * @param $module_name
  2162. * the name of the module being installed.
  2163. *
  2164. * @returns
  2165. * nothing
  2166. *
  2167. * @ingroup tripal_files_api
  2168. */
  2169. function tripal_create_moddir($module_name) {
  2170. // make the data directory for this module
  2171. $data_dir = file_directory_path() . "/tripal/$module_name";
  2172. if (!file_check_directory($data_dir, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
  2173. $message = "Cannot create directory $data_dir. This module may not ".
  2174. "behave correctly without this directory. Please create ".
  2175. "the directory manually or fix the problem and reinstall.";
  2176. drupal_set_message(check_plain(t($message)), 'error');
  2177. watchdog('tripal_core', $message, array(), WATCHDOG_ERROR);
  2178. }
  2179. }
  2180. /**
  2181. * Each Tripal module has a unique data directory which was creatd using the
  2182. * tripal_create_moddir function during installation. This function
  2183. * retrieves the directory path.
  2184. *
  2185. * @param $module_name
  2186. * The name of the module
  2187. *
  2188. * @returns
  2189. * The path within the Drupal installation where the data directory resides
  2190. * @ingroup tripal_files_api
  2191. */
  2192. function tripal_get_moddir($module_name) {
  2193. $data_dir = file_directory_path() . "/tripal/$module_name";
  2194. return $data_dir;
  2195. }
  2196. /**
  2197. * Set the Tripal Database
  2198. *
  2199. * The tripal_db_set_active function is used to prevent namespace collisions
  2200. * when chado and drupal are installed in the same database but in different
  2201. * schemas. It is also used for backwards compatibility with older versions
  2202. * of tripal or in cases where chado is located outside of the Drupal database.
  2203. *
  2204. * @ingroup tripal_chado_api
  2205. */
  2206. function tripal_db_set_active($dbname) {
  2207. global $db_url, $db_type;
  2208. $chado_exists = 0;
  2209. // only postgres can support search paths. So if this is MysQL then
  2210. // just run the normal tripal_db_set_active function.
  2211. if (strcmp($db_type, 'pgsql')==0) {
  2212. // if the 'chado' database is in the $db_url variable then chado is
  2213. // not in the same Drupal database
  2214. if (is_array($db_url)) {
  2215. if (isset($db_url[$dbname])) {
  2216. return db_set_active($dbname);
  2217. }
  2218. }
  2219. // if this is the default database then set the search path and return
  2220. if (strcmp($dbname, 'default')==0) {
  2221. // tripal_db_set_default_search_path();
  2222. return db_set_active($dbname);
  2223. }
  2224. // if the user requests a database other than the default
  2225. // then we need to try and set the chado search path. This
  2226. // only works if Chado is local to the Drpual database. If it
  2227. // fails then we assume the database is not local and we'll
  2228. // set it as normal.
  2229. else {
  2230. // if (tripal_db_set_chado_search_path($dbname)) {
  2231. return $dbname;
  2232. // }
  2233. // else {
  2234. // return db_set_active($dbname);
  2235. // }
  2236. }
  2237. }
  2238. else {
  2239. return db_set_active($dbname);
  2240. }
  2241. }
  2242. /**
  2243. * Set the chado search_path for PostgreSQL
  2244. *
  2245. * Sets the database search_path for postgreSQL to the
  2246. * chado schema.
  2247. *
  2248. * @ingroup tripal_chado_api
  2249. */
  2250. function tripal_db_set_chado_search_path($dbname) {
  2251. // check to make sure the chado schema exists
  2252. $chado_exists = variable_get('chado_schema_exists', FALSE);
  2253. if(!$chado_exists){
  2254. $chado_exists = tripal_core_chado_schema_exists();
  2255. }
  2256. // here we make the assumption that the default database schema is
  2257. // 'public'. This will most likely always be the case but if not,
  2258. // then this code will break
  2259. if ($chado_exists) {
  2260. db_query('set search_path to %s', "$dbname,public");
  2261. return TRUE;
  2262. }
  2263. else {
  2264. return FALSE;
  2265. }
  2266. }
  2267. /**
  2268. * Set the default search_path for PostgreSQL
  2269. *
  2270. * Sets the database search_path for postgreSQL to the
  2271. * default schema.
  2272. *
  2273. * @ingroup tripal_chado_api
  2274. */
  2275. function tripal_db_set_default_search_path() {
  2276. // we make the assumption that the default schema is 'public'.
  2277. db_query('set search_path to %s', 'public');
  2278. }
  2279. /**
  2280. * Indicates if the SQL statement is prepapred
  2281. *
  2282. * @param $statement_name
  2283. * The name of the statement to check if it is prepared.
  2284. *
  2285. * @return
  2286. * TRUE if the statement is preapred, FALSE otherwise
  2287. */
  2288. function tripal_core_is_sql_prepared($statement_name) {
  2289. // to reduce the need for a database query we will check the
  2290. // session variable for this connection to see if the statement
  2291. // has been prepared. If it has then we won't do the database
  2292. // query to find out. If it hasn't then we'll query the database
  2293. // to see if it is prepared.
  2294. $connection = unserialize(variable_get('tripal_persistent_chado', NULL));
  2295. if (!isset($_SESSION[$connection])) {
  2296. $_SESSION[$connection] = array();
  2297. }
  2298. if(in_array($statement_name,$_SESSION[$connection])){
  2299. //print "Is Prepared and in Session var: $statement_name\n";
  2300. return TRUE;
  2301. }
  2302. // @coder-ignore: acting on postgres tables rather then drupal schema therefore, table prefixing does not apply
  2303. $sql = "SELECT name FROM pg_prepared_statements WHERE name = '%s'";
  2304. // do not use 'chado_query' here or it causes memory-leaks
  2305. $result = db_fetch_object(db_query($sql, $statement_name));
  2306. if ($result) {
  2307. $_SESSION[$connection][] = $statement_name;
  2308. //print "Is Prepared but in DB: $statement_name\n";
  2309. return TRUE;
  2310. }
  2311. //print "Is Not prepared: $statement_name\n";
  2312. return FALSE;
  2313. }
  2314. /**
  2315. * Prepare a chado query
  2316. *
  2317. * @param $statement_name
  2318. * The name of the prepared statement
  2319. * @param $psql
  2320. * The SQL statement to be executed via chado_query.
  2321. * Should be of the form PREPARE <statement name> AS <SQL Statement to be prepared>
  2322. * @param $args
  2323. * An array of arguements required to execute the prepared statement. The keys of
  2324. * the array should correspond to the $\d in the prepare statement and the value should
  2325. * be the type of value needed (ie: text, int, etc.)
  2326. */
  2327. function tripal_core_chado_prepare($statement_name, $psql, $args) {
  2328. $connection = unserialize(variable_get('tripal_persistent_chado', NULL));
  2329. // Check to see if this statement was already prepared
  2330. if (tripal_core_is_sql_prepared($statement_name)) {
  2331. //if it was check that the arguments are the same
  2332. $prepared_args = $_SESSION['prepared_args'][$connection][$statement_name];
  2333. $prepared_sql = $_SESSION['prepared_sql'][$connection][$statement_name];
  2334. if ($prepared_args == $args) {
  2335. // This statement is already prepared
  2336. return TRUE;
  2337. }
  2338. else {
  2339. // Although a statement with this name is already prepared it is not the same!
  2340. 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);
  2341. return FALSE;
  2342. }
  2343. }
  2344. $status = chado_query($psql);
  2345. if (!$status) {
  2346. watchdog('tripal_core', "chado_prepare: not able to prepare '%name' statement for: %sql", array('%name' => $statement_name, '%sql' => $psql), WATCHDOG_ERROR);
  2347. return FALSE;
  2348. }
  2349. else {
  2350. watchdog('tripal_core', "tripal_core_chado_select: prepared '%name' statement as %sql", array('%name' => $statement_name, '%sql' => $psql), WATCHDOG_NOTICE);
  2351. $_SESSION[$connection][] = $statement_name;
  2352. $_SESSION['prepared_args'][$connection][$statement_name] = $args;
  2353. $_SESSION['prepared_sql'][$connection][$statement_name] = $psql;
  2354. return TRUE;
  2355. }
  2356. }
  2357. /**
  2358. * Execute a prepared statement with the supplied values
  2359. *
  2360. * @param $statement_name
  2361. * The name of the prepared statement
  2362. * @param $sql
  2363. * The SQL to execute using chado query.
  2364. * Should be of the form EXECUTE <statement_name> (<arg1>,<arg2>...<argn>)
  2365. * @param $values
  2366. * An array of values in the execute sql statement
  2367. */
  2368. function tripal_core_chado_execute_prepared($statement_name, $sql, $values) {
  2369. $connection = unserialize(variable_get('tripal_persistent_chado', NULL));
  2370. if (!tripal_core_is_sql_prepared($statement_name)) {
  2371. watchdog('tripal_core', "tripal_core_chado_execute_prepared: Cannot execute an unprepared statement: '%name'", array('%name' => $statement_name), WATCHDOG_ERROR);
  2372. }
  2373. // Before Executing, Ensure that all the values are supplied
  2374. $required_values = $_SESSION['prepared_args'][$connection][$statement_name];
  2375. if (!$required_values){
  2376. watchdog('tripal_core', "tripal_core_chado_execute_prepared: missing prepare arguments for this statement: '%name'", array('%name' => $statement_name), WATCHDOG_ERROR);
  2377. }
  2378. if (sizeof($required_values) == sizeof($values)) {
  2379. $error = FALSE;
  2380. foreach ($values as $k => $v) {
  2381. if (isset($required_values[$k])) {
  2382. switch ($required_values[$k]) {
  2383. case 'text':
  2384. $check = is_string($v);
  2385. if (!$check) {
  2386. watchdog('tripal_core', "chado_execute_prepared: wrong argument type supplied for '%name' statement. Expected %required but recieved '%value'",
  2387. array('%name' => $statement_name, '%required' => $required_values[$k], '%value' => print_r($v,TRUE)), WATCHDOG_ERROR);
  2388. return FALSE;
  2389. }
  2390. break;
  2391. case 'int':
  2392. $check = is_numeric($v);
  2393. if (!$check) {
  2394. watchdog('tripal_core', "chado_execute_prepared: wrong argument type supplied for '%name' statement. Expected %required but recieved '%value'",
  2395. array('%name' => $statement_name, '%required' => $required_values[$k], '%value' => print_r($v,TRUE)), WATCHDOG_ERROR);
  2396. return FALSE;
  2397. }
  2398. break;
  2399. case 'bool':
  2400. if($v != 'TRUE' and $v != 'FALSE'){
  2401. watchdog('tripal_core', "chado_execute_prepared: wrong argument type supplied for '%name' statement. Expected %required but recieved '%value'",
  2402. array('%name' => $statement_name, '%required' => $required_values[$k], '%value' => print_r($v,TRUE)), WATCHDOG_ERROR);
  2403. return FALSE;
  2404. }
  2405. break;
  2406. case 'numeric':
  2407. $check = is_numeric($v);
  2408. if (!$check) {
  2409. watchdog('tripal_core', "chado_execute_prepared: wrong argument type supplied for '%name' statement. Expected %required but recieved '%value'",
  2410. array('%name' => $statement_name, '%required' => $required_values[$k], '%value' => print_r($v,TRUE)), WATCHDOG_ERROR);
  2411. return FALSE;
  2412. }
  2413. break;
  2414. default:
  2415. watchdog('tripal_core', "chado_execute_prepared: unsupported argument type (supplied for '%name' statement %type)",
  2416. array('%name' => $statement_name, '%type' => $required_values[$k]), WATCHDOG_WARNING);
  2417. break;
  2418. }
  2419. }
  2420. else {
  2421. watchdog('tripal_core', "chado_execute_prepared: wrong number of arguments supplied for '%name' statement. Expected %required but recieved %values",
  2422. array('%name' => $statement_name, '%required' => print_r($required_values,TRUE), '%values' => print_r($values,TRUE)), WATCHDOG_ERROR);
  2423. return FALSE;
  2424. }
  2425. }
  2426. // Since all values are supplied, execute
  2427. $resource = chado_query($sql, $values);
  2428. return $resource;
  2429. }
  2430. else {
  2431. watchdog('tripal_core', "chado_execute_prepared: wrong number of arguments supplied for '%name' statement. Expected %required but recieved %values",
  2432. array('%name' => $statement_name, '%required' => print_r($required_values,TRUE), '%values' => print_r($values,TRUE)), WATCHDOG_ERROR);
  2433. return FALSE;
  2434. }
  2435. }
  2436. /**
  2437. * Instantiate or Return a persistent chado connection
  2438. *
  2439. * NOTE: cannot use $active_db since a new connection is created each time
  2440. * db_set_active() is called
  2441. *
  2442. * @return
  2443. * A postgresql connection object which can be used by pg_prepare, pg_execute, etc.
  2444. */
  2445. function tripal_db_persistent_chado() {
  2446. global $db_url;
  2447. // get connection if it already exists
  2448. // Otherwise we need to set it
  2449. $sconn = variable_get('tripal_persistent_chado', NULL);
  2450. if ($sconn) {
  2451. return unserialize($sconn);
  2452. }
  2453. else {
  2454. if (is_array($db_url) && isset($db_url['chado'])) {
  2455. $connection = db_connect($db_url['chado']);
  2456. if (!$connection) {
  2457. watchdog('tripal_core', "Could not create persistant connection", array(), WATCHDOG_ERROR);
  2458. return FALSE;
  2459. }
  2460. variable_set('tripal_persistent_chado', serialize($connection));
  2461. }
  2462. else {
  2463. $connection = db_connect($db_url);
  2464. if (!$connection) {
  2465. watchdog('tripal_core', "Could not create persistant connection", array(), WATCHDOG_ERROR);
  2466. return FALSE;
  2467. }
  2468. variable_set('tripal_persistent_chado', serialize($connection));
  2469. }
  2470. return $connection;
  2471. }
  2472. return FALSE;
  2473. }
  2474. /**
  2475. * Release a persistent chado connection
  2476. */
  2477. function tripal_db_release_persistent_chado() {
  2478. variable_del('tripal_persistent_chado');
  2479. }
  2480. /**
  2481. * Start a transaction block. Ensures the use of a persistent chado connection
  2482. */
  2483. function tripal_db_start_transaction() {
  2484. $connection = tripal_db_persistent_chado();
  2485. chado_query("BEGIN");
  2486. }
  2487. /**
  2488. * Set a savepoint to roll the current transaction back to if an error is encountered
  2489. */
  2490. function tripal_db_set_savepoint_transaction($savepoint, $release = FALSE) {
  2491. // Postgresql requires a savepoint of the same name to be unset before re-use
  2492. if ($release) {
  2493. chado_query("RELEASE SAVEPOINT %s", $savepoint);
  2494. }
  2495. chado_query("SAVEPOINT %s", $savepoint);
  2496. }
  2497. /**
  2498. * Commit changes made during the current transaction
  2499. */
  2500. function tripal_db_commit_transaction() {
  2501. chado_query("COMMIT");
  2502. }
  2503. /**
  2504. * Rollback changes.
  2505. *
  2506. * If $savepoint is NULL then rollback to the beginning of the transaction,
  2507. * Otherwise, rollback to the point at which the named $savepoint was created
  2508. *
  2509. * @param $savepoint
  2510. * The name of the saved point in the transaction to rollback to
  2511. */
  2512. function tripal_db_rollback_transaction($savepoint = NULL, $commit = TRUE) {
  2513. if ($savepoint) {
  2514. chado_query("ROLLBACK TO SAVEPOINT %s", $savepoint);
  2515. }
  2516. else {
  2517. chado_query("ROLLBACK");
  2518. }
  2519. if ($commit) {
  2520. tripal_db_commit_transaction();
  2521. }
  2522. }
  2523. /**
  2524. * Purpose: Get max rank for a given set of criteria
  2525. * This function was developed with the many property tables in chado in mind
  2526. *
  2527. * @param $tablename
  2528. * The name of the chado table you want to select the max rank from this table must contain a
  2529. * rank column of type integer
  2530. * @param $where_options
  2531. * where options should include the id and type for that table to correctly
  2532. * group a set of records together where the only difference are the value and rank
  2533. * @code
  2534. * array(
  2535. * <column_name> => array(
  2536. * 'type' => <type of column: INT/STRING>,
  2537. * 'value' => <the value you want to filter on>,
  2538. * 'exact' => <if TRUE use =; if FALSE use ~>,
  2539. * )
  2540. * )
  2541. * @endcode
  2542. * @return the maximum rank
  2543. *
  2544. * @ingroup tripal_chado_api
  2545. */
  2546. function tripal_get_max_chado_rank($tablename, $where_options) {
  2547. $where= array();
  2548. //generate the where clause from supplied options
  2549. // the key is the column name
  2550. foreach ($where_options as $key => $val_array) {
  2551. if (preg_match('/INT/', $val_array['type'])) {
  2552. $where[] = $key . "=" . $val_array['value'];
  2553. }
  2554. else {
  2555. if ($val_array['exact']) {
  2556. $operator='=';
  2557. }
  2558. else {
  2559. $operator='~';
  2560. }
  2561. $where[] = $key . $operator . "'" . $val_array['value'] . "'";
  2562. }
  2563. }
  2564. $previous_db = tripal_db_set_active('chado');
  2565. $result = db_fetch_object(db_query(
  2566. "SELECT max(rank) as max_rank, count(rank) as count FROM %s WHERE %s",
  2567. $tablename,
  2568. implode(' AND ', $where)
  2569. ));
  2570. tripal_db_set_active($previous_db);
  2571. //drupal_set_message("Max Rank Query=SELECT max(rank) as max_rank, count(rank) as count FROM ".$tablename." WHERE ".implode(' AND ',$where));
  2572. if ($result->count > 0) {
  2573. return $result->max_rank;
  2574. }
  2575. else {
  2576. return -1;
  2577. }
  2578. }
  2579. /**
  2580. * Retrieves the schema in an array for the specified custom table.
  2581. *
  2582. * @param $table
  2583. * The name of the table to create.
  2584. *
  2585. * @return
  2586. * A Drupal-style Schema API array definition of the table. Returns
  2587. * FALSE on failure.
  2588. *
  2589. * @ingroup tripal_core_api
  2590. */
  2591. function tripal_get_chado_custom_schema($table) {
  2592. $sql = "SELECT schema FROM {tripal_custom_tables} WHERE table_name = '%s'";
  2593. $custom = db_fetch_object(db_query($sql, $table));
  2594. if (!$custom) {
  2595. return FALSE;
  2596. }
  2597. else {
  2598. return unserialize($custom->schema);
  2599. }
  2600. }
  2601. /**
  2602. * Check that the Chado schema exists
  2603. *
  2604. * @return
  2605. * TRUE/FALSE depending upon whether it exists
  2606. */
  2607. function tripal_core_chado_schema_exists() {
  2608. $exists = variable_get('chado_schema_exists', FALSE);
  2609. if(!$exists) {
  2610. // This is postgresql-specific code to check the existence of the chado schema
  2611. // @coder-ignore: acting on pg_catalog schema rather then drupal schema therefore, table prefixing does not apply
  2612. $sql = "SELECT nspname FROM pg_catalog.pg_namespace WHERE nspname = 'chado'";
  2613. if (db_fetch_object(db_query($sql))) {
  2614. variable_set('chado_schema_exists', TRUE);
  2615. return TRUE;
  2616. }
  2617. else {
  2618. return FALSE;
  2619. }
  2620. }
  2621. return TRUE;
  2622. }
  2623. /**
  2624. * Retrieves the list tables in the Chado schema. By default it only retursn
  2625. * the default Chado tables, but may also return custom tables added to the
  2626. * Chado schema as well.
  2627. *
  2628. * @param $include_custom
  2629. * Optional. Set as TRUE to include any custom tables created in the
  2630. * Chado schema. Custom tables are added to Chado using the
  2631. * tripal_core_chado_create_table() function.
  2632. *
  2633. * @returns
  2634. * An associative array where the key and value pairs are the Chado table names.
  2635. *
  2636. * @ingroup tripal_core_api
  2637. */
  2638. function tripal_core_get_chado_tables($include_custom = NULL) {
  2639. if (is_array($db_url) AND array_key_exists('chado', $db_url)) {
  2640. $previous_db = tripal_db_set_active('chado');
  2641. // @coder-ignore: acting on pg_catalog schema rather then drupal schema therefore, table prefixing does not apply
  2642. $sql = 'SELECT tablename FROM pg_tables';
  2643. $resource = db_query($sql);
  2644. tripal_db_set_active($previous_db);
  2645. }
  2646. else {
  2647. // @coder-ignore: acting on pg_catalog schema rather then drupal schema therefore, table prefixing does not apply
  2648. $sql = "SELECT tablename FROM pg_tables WHERE schemaname='chado'";
  2649. $resource = db_query($sql);
  2650. }
  2651. $tables = array();
  2652. while ($r = db_fetch_object($resource)) {
  2653. $tables[$r->tablename] = $r->tablename;
  2654. }
  2655. // now add in the custom tables too
  2656. if ($include_custom) {
  2657. $sql = "SELECT table_name FROM {tripal_custom_tables}";
  2658. $resource = db_query($sql);
  2659. }
  2660. while ($r = db_fetch_object($resource)) {
  2661. $tables[$r->table_name] = $r->table_name;
  2662. }
  2663. asort($tables);
  2664. return $tables;
  2665. }
  2666. /**
  2667. * Sets a Drupal variable with the current version of Chado. This variable
  2668. * can then be queried later using the tripal_core_get_chado_Version
  2669. *
  2670. * @returns
  2671. * The version of Chado
  2672. *
  2673. * @ingroup tripal_core_api
  2674. */
  2675. function tripal_core_set_chado_version() {
  2676. global $db_url;
  2677. // check that Chado is installed if not return 'uninstalled as the version'
  2678. $chado_exists = tripal_core_chado_schema_exists();
  2679. if (!$chado_exists) {
  2680. // if it's not in the drupal database check to see if it's specified in the $db_url
  2681. // in the settings.php
  2682. if (!array_key_exists('chado', $db_url)) {
  2683. // if it's not in the drupal database or specified in the $db_url then
  2684. // return uninstalled as the version
  2685. return 'not installed';
  2686. }
  2687. }
  2688. // if the table doesn't exist then we don't know what version but we know
  2689. // it must be 1.11 or older.
  2690. $previous_db = tripal_db_set_active('chado');
  2691. $prop_exists = db_table_exists('chadoprop');
  2692. tripal_db_set_active($previous_db);
  2693. if (!$prop_exists) {
  2694. return "1.11 or older";
  2695. }
  2696. // we can't use the Tripal API to query this table
  2697. // because the Tripal API depends on this fucntion to
  2698. // tell it the version. So, we need a typical SQL statement
  2699. $sql = "SELECT value "
  2700. ."FROM chadoprop CP "
  2701. ." INNER JOIN cvterm CVT on CVT.cvterm_id = CP.type_id "
  2702. ." INNER JOIN cv CV on CVT.cv_id = CV.cv_id "
  2703. ."WHERE CV.name = 'chado_properties' and CVT.name = 'version'";
  2704. $previous_db = tripal_db_set_active('chado');
  2705. $v = db_fetch_object(db_query($sql));
  2706. tripal_db_set_active($previous_db);
  2707. // if we don't have a version in the chadoprop table then it must be
  2708. // v1.11 or older
  2709. if (!$v->value) {
  2710. variable_set('chado_version', "1.11 or older");
  2711. return "1.11 or older";
  2712. }
  2713. variable_set('chado_version', $v->value);
  2714. return $v->value;
  2715. }
  2716. /**
  2717. * Returns the version number of the currently installed Chado instance.
  2718. * It can return the real or effective version.
  2719. *
  2720. * @param $exact
  2721. * Set this argument to 1 to retrieve the exact version that is installed.
  2722. * Otherwise, this function will set the version to the nearest 'tenth'.
  2723. * Chado versioning numbers in the hundreds represent changes to the
  2724. * software and not the schema. Changes in the tenth's represent changes
  2725. * in the schema.
  2726. *
  2727. * @param $warn_if_unsupported
  2728. * If the currently installed version of Chado is not supported by Tripal
  2729. * the generatea a Drupal warning.
  2730. *
  2731. * @returns
  2732. * The version of Chado
  2733. *
  2734. * @ingroup tripal_core_api
  2735. */
  2736. function tripal_core_get_chado_version($exact = FALSE, $warn_if_unsupported = FALSE) {
  2737. // first get the chado version that is installed
  2738. $exact_version = variable_get('chado_version', '');
  2739. if (!$exact_version) {
  2740. $exact_version = tripal_core_set_chado_version();
  2741. }
  2742. // Tripal only supports v1.11 or newer.. really this is the same as v1.1
  2743. // but at the time the v1.11 schema API was written we didn't know that so
  2744. // we'll return the version 1.11 so the schema API will work.
  2745. if (strcmp($exact_version, '1.11 or older') == 0) {
  2746. $exact_version = "1.11";
  2747. if($warn_if_unsupported){
  2748. drupal_set_message(t("WARNING: Tripal does not fully support Chado version less than v1.1. If you are certain this is v1.1
  2749. of if Chado was installed using an earlier version of Tripal then all is well. If not please upgrade to v1.1 or later"),
  2750. 'warning');
  2751. }
  2752. }
  2753. // if not returing an exact version, return the version to the nearest 10th.
  2754. // return 1.2 for all versions of 1.2x
  2755. $effective_version = $exact_version;
  2756. if (preg_match('/^1\.2\d+$/', $effective_version)){
  2757. $effective_version = "1.2";
  2758. }
  2759. if ($warn_if_unsupported and ($effective_version != 1.11 and $effective_version != 1.2)) {
  2760. drupal_set_message(t("WARNING: The currently installed version of Chado, v$exact_version, is not fully compatible with Tripal."),'warning');
  2761. }
  2762. // if the callee has requested the exact version then return it
  2763. if ($exact) {
  2764. return $exact_version;
  2765. }
  2766. return $effective_version;
  2767. }
  2768. /**
  2769. * Retrieves the chado tables Schema API array.
  2770. *
  2771. * @param $table
  2772. * The name of the table to retrieve. The function will use the appopriate
  2773. * Tripal chado schema API hooks (e.g. v1.11 or v1.2).
  2774. *
  2775. * @returns
  2776. * A Drupal Schema API array defining the table.
  2777. *
  2778. * @ingroup tripal_core_api
  2779. */
  2780. function tripal_core_get_chado_table_schema($table) {
  2781. // first get the chado version that is installed
  2782. $v = tripal_core_get_chado_version();
  2783. // get the table array from the proper chado schema
  2784. $v = preg_replace("/\./", "_", $v); // reformat version for hook name
  2785. $table_arr = module_invoke_all("chado_schema_v" . $v . "_" . $table);
  2786. // if the table_arr is empty then maybe this is a custom table
  2787. if(!is_array($table_arr) or count($table_arr) == 0){
  2788. $table_arr = tripal_get_chado_custom_schema($table);
  2789. }
  2790. return $table_arr;
  2791. }
  2792. /**
  2793. * This function will delete Drupal nodes for any sync'ed table (e.g.
  2794. * feature, organism, analysis, stock, library) if the chado record has been
  2795. * deleted or the entry in the chado_[table] table has been removed.
  2796. *
  2797. * @param $table
  2798. * The name of the table that corresonds to the node type we want to clean up.
  2799. * @param $job_id
  2800. * This should be the job id from the Tripal jobs system. This function
  2801. * will update the job status using the provided job ID.
  2802. *
  2803. * @ingroup tripal_core_api
  2804. */
  2805. function tripal_core_clean_orphaned_nodes($table, $job_id) {
  2806. $count = 0;
  2807. // build the SQL statments needed to check if nodes point to valid analyses
  2808. $dsql = "SELECT * FROM {node} WHERE type = 'chado_%s' order by nid";
  2809. $nsql = "SELECT * FROM {node} WHERE nid = %d";
  2810. $csql = "SELECT * FROM {chado_%s} where nid = %d ";
  2811. $clsql= "SELECT * FROM {chado_%s}";
  2812. $lsql = "SELECT * FROM %s where %s_id = %d ";
  2813. // load into nodes array
  2814. print "Getting nodes\n";
  2815. $nodes = array();
  2816. $res = db_query($dsql, $table);
  2817. while ($node = db_fetch_object($res)) {
  2818. $nodes[$count] = $node;
  2819. $count++;
  2820. }
  2821. // load the chado_$table into an array
  2822. print "Getting chado_$table\n";
  2823. $cnodes = array();
  2824. $res = db_query($clsql, $table);
  2825. while ($node = db_fetch_object($res)) {
  2826. $cnodes[$count] = $node;
  2827. $count++;
  2828. }
  2829. $interval = intval($count * 0.01);
  2830. if ($interval < 1) {
  2831. $interval = 1;
  2832. }
  2833. // iterate through all of the chado_$table entries and remove those
  2834. // that don't have a node or don't have a $table record in chado.libary
  2835. foreach ($cnodes as $nid) {
  2836. // update the job status every 1% analyses
  2837. if ($job_id and $i % $interval == 0) {
  2838. tripal_job_set_progress($job_id, intval(($i / $count) * 100));
  2839. }
  2840. // see if the node exits, if not remove the entry from the chado_$table table
  2841. $node = db_fetch_object(db_query($nsql, $nid->nid));
  2842. if (!$node) {
  2843. db_query("DELETE FROM {chado_%s} WHERE nid = %d", $table, $nid->nid);
  2844. $message = "chado_$table missing node.... DELETING: $nid->nid";
  2845. watchdog('tripal_core', $message, array(), WATCHDOG_WARNING);
  2846. }
  2847. // see if the record in chado exist, if not remove the entry from the chado_$table
  2848. $table_id = $table . "_id";
  2849. $record = db_fetch_object(chado_query($lsql, $table, $table, $nid->$table_id));
  2850. if (!$record) {
  2851. chado_query("DELETE FROM {chado_%s} WHERE %s_id = '%d'", $table, $table, $nid->$table_id);
  2852. $message = "chado_$table missing $table.... DELETING entry.";
  2853. watchdog('tripal_core', $message, array(), WATCHDOG_WARNING);
  2854. }
  2855. $i++;
  2856. }
  2857. // iterate through all of the nodes and delete those that don't
  2858. // have a corresponding entry in chado_$table
  2859. foreach ($nodes as $node) {
  2860. // update the job status every 1% libraries
  2861. if ($job_id and $i % $interval == 0) {
  2862. tripal_job_set_progress($job_id, intval(($i / $count) * 100));
  2863. }
  2864. // check to see if the node has a corresponding entry
  2865. // in the chado_$table table. If not then delete the node.
  2866. $link = db_fetch_object(db_query($csql, $table, $node->nid));
  2867. if (!$link) {
  2868. if (node_access('delete', $node)) {
  2869. $message = "Node missing in chado_$table table.... DELETING node $node->nid";
  2870. watchdog("tripal_core", $message, array(), WATCHDOG_WARNING);
  2871. node_delete($node->nid);
  2872. }
  2873. else {
  2874. $message = "Node missing in chado_$table table.... but cannot delete due to improper permissions (node $node->nid)";
  2875. watchdog("tripal_core", $message, array(), WATCHDOG_WARNING);
  2876. }
  2877. }
  2878. $i++;
  2879. }
  2880. return '';
  2881. }