tripal_core_chado.api.inc 107 KB

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