tripal_core.api.inc 101 KB

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