tripal_core.api.inc 110 KB

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