tripal_core_chado.api.inc 116 KB

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