tripal_core.api.inc 112 KB

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