tripal_core.api.inc 118 KB

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