tripal_core.api.inc 128 KB

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