tripal_core.api.inc 108 KB

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