tripal_core.api.inc 113 KB

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