tripal_core.api.inc 117 KB

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