tripal_core_chado.api.inc 106 KB

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