tripal_core.api.inc 130 KB

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