tripal_core_chado.api.inc 140 KB

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