tripal_core.api.inc 115 KB

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