tripal_core_chado.api.inc 103 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875
  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. if (!array_key_exists('return_sql', $options)) {
  732. $options['return_sql'] = FALSE;
  733. }
  734. if (!array_key_exists('has_record', $options)) {
  735. $options['has_record'] = FALSE;
  736. }
  737. if (!array_key_exists('is_duplicate', $options)) {
  738. $options['is_duplicate'] = FALSE;
  739. }
  740. $pager = array();
  741. if (array_key_exists('pager', $options)) {
  742. $pager = $options['pager'];
  743. }
  744. // check that our columns and values arguments are proper arrays
  745. if (!is_array($columns)) {
  746. watchdog('tripal_core', 'the $columns argument for tripal_core_chado_select must be an array.');
  747. return FALSE;
  748. }
  749. if (!is_array($values)) {
  750. watchdog('tripal_core', 'the $values argument for tripal_core_chado_select must be an array.');
  751. return FALSE;
  752. }
  753. // get the table description
  754. $table_desc = tripal_core_get_chado_table_schema($table);
  755. $select = '';
  756. $from = '';
  757. $where = array();
  758. $args = array();
  759. // if the 'use_unique' option is turned on then we want
  760. // to remove all but unique keys
  761. if ($options['is_duplicate'] and array_key_exists('unique keys', $table_desc)) {
  762. $ukeys = $table_desc['unique keys'];
  763. $has_results = 0;
  764. // iterate through the unique constraints and reset the values and columns
  765. // arrays to only include these fields
  766. foreach ($ukeys as $cname => $fields) {
  767. if ($has_results) {
  768. continue;
  769. }
  770. $new_values = array();
  771. $new_columns = array();
  772. $new_options = array();
  773. $uq_sname = "uq_" . $table . "_";
  774. $has_pkey = 0;
  775. // include the primary key in the results returned
  776. if (array_key_exists('primary key', $table_desc)) {
  777. $has_pkey = 1;
  778. $pkeys = $table_desc['primary key'];
  779. foreach ($pkeys as $index => $key) {
  780. array_push($new_columns, $key);
  781. }
  782. }
  783. // recreate the $values and $columns arrays
  784. foreach ($fields as $field) {
  785. if (array_key_exists($field, $values)) {
  786. $new_values[$field] = $values[$field];
  787. $uq_sname .= substr($field, 0, 2);
  788. // if there is no primary key then use the unique contraint fields
  789. if (!$has_pkey) {
  790. array_push($new_columns, $field);
  791. }
  792. }
  793. // if the field doesn't exist in the values array then
  794. // substitute any default values
  795. elseif (array_key_exists('default', $table_desc['fields'][$field])) {
  796. $new_values[$field] = $table_desc['fields'][$field]['default'];
  797. $uq_sname .= substr($field, 0, 2);
  798. if (!$has_pkey) {
  799. array_push($new_columns, $field);
  800. }
  801. }
  802. // if there is no value (default or otherwise) check if this field is
  803. // allowed to be null
  804. elseif (!$table_desc['fields'][$field]['not null']) {
  805. $new_values[$field] = NULL;
  806. $uq_sname .= "n" . substr($field, 0, 2);
  807. if (!$has_pkey) {
  808. array_push($new_columns, $field);
  809. }
  810. }
  811. // if the array key doesn't exist in the values given by the caller
  812. // and there is no default value then we cannot check if the record
  813. // is a duplicate so return FALSE
  814. else {
  815. watchdog('tripal_core', "tripal_core_chado_select: There is no value for %field"
  816. . " thus we cannot check if this record is unique",
  817. array('%field' => $field), WATCHDOG_ERROR);
  818. return FALSE;
  819. }
  820. }
  821. $new_options['statement_name'] = $uq_sname;
  822. $results = tripal_core_chado_select($table, $new_columns, $new_values, $new_options);
  823. // if we have a duplicate record then return the results
  824. if (count($results) > 0) {
  825. $has_results = 1;
  826. }
  827. unset($new_columns);
  828. unset($new_values);
  829. unset($new_options);
  830. }
  831. if ($options['has_record'] and $has_results) {
  832. return TRUE;
  833. }
  834. else {
  835. return $results;
  836. }
  837. }
  838. foreach ($values as $field => $value) {
  839. // make sure the field is in the table description. If not then return an error
  840. // message
  841. if (!array_key_exists($field, $table_desc['fields'])) {
  842. watchdog('tripal_core', "tripal_core_chado_select: The field '%field' does not exist " .
  843. "for the table '%table'. Cannot perform query. Values: %array",
  844. array('%field' => $field, '%table' => $table, '%array' => print_r($values, 1)), WATCHDOG_ERROR);
  845. return array();
  846. }
  847. $select[] = $field;
  848. if (is_array($value)) {
  849. // if the user has specified multiple values for matching then this we
  850. // want to catch that and save them in our $where array, otherwise
  851. // we'll descend for a foreign key relationship
  852. if (array_values($value) === $value) {
  853. $where[$field] = $value;
  854. }
  855. else {
  856. // select the value from the foreign key relationship for this value
  857. $foreign_options = array(
  858. 'regex_columns' => $options['regex_columns'],
  859. );
  860. $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value, $foreign_options);
  861. if (!$results or count($results)==0) {
  862. return array();
  863. }
  864. else {
  865. $where[$field] = $results;
  866. }
  867. }
  868. }
  869. else {
  870. // need to catch a 0 and make int if integer field
  871. // but we don't want to catch a NULL
  872. if ($value === NULL) {
  873. $where[$field] = NULL;
  874. }
  875. elseif ($table_desc['fields'][$field]['type'] == 'int') {
  876. $where[$field][] = (int) $value;
  877. }
  878. else {
  879. $where[$field][] = $value;
  880. }
  881. }
  882. }
  883. // now build the SQL and prepared SQL statements. We may not use
  884. // the prepared statement if it wasn't requested in the options or if the
  885. // argument in a where statement has multiple values.
  886. if (empty($where)) {
  887. // sometimes want to select everything
  888. $sql = "SELECT " . implode(', ', $columns) . " ";
  889. $sql .= 'FROM {' . $table . '} ';
  890. // we don't prepare a statement if there is no where clause
  891. $prepared = FALSE;
  892. }
  893. else {
  894. $sql = "SELECT " . implode(', ', $columns) . " ";
  895. $sql .= 'FROM {' . $table . '} ';
  896. // if $values is empty then we want all results so no where clause
  897. if (!empty($values)) {
  898. $sql .= "WHERE ";
  899. }
  900. foreach ($where as $field => $value) {
  901. // if we have multiple values returned then we need an 'IN' statement
  902. // in our where statement
  903. if (count($value) > 1) {
  904. $sql .= "$field IN (";
  905. $index = 0;
  906. foreach ($value as $v) {
  907. $sql .= ":$field" . $index . ', ';
  908. $args[":$field" . $index] = $v;
  909. $index++;
  910. }
  911. $sql = drupal_substr($sql, 0, -2); // remove trailing ', '
  912. $sql .= ") AND ";
  913. }
  914. // if we have a null value then we need an IS NULL in our where statement
  915. elseif ($value === NULL) {
  916. $sql .= "$field IS NULL AND ";
  917. // Need to remove one from the argument count b/c nulls don't add an argument
  918. }
  919. // if we have a single value then we need an = in our where statement
  920. else {
  921. $operator = '=';
  922. if (in_array($field, $options['regex_columns'])) {
  923. $operator = '~*';
  924. }
  925. if (in_array($field, $options['case_insensitive_columns'])) {
  926. $sql .= "lower($field) $operator lower(:$field) AND ";
  927. $args[":$field"] = $value[0];
  928. }
  929. else {
  930. $sql .= "$field $operator :$field AND ";
  931. $args[":$field"] = $value[0];
  932. }
  933. }
  934. } // end foreach item in where clause
  935. $sql = drupal_substr($sql, 0, -4); // get rid of the trailing 'AND '
  936. } // end if (empty($where)){ } else {
  937. // finally add any ordering of the results to the SQL statement
  938. if (count($options['order_by']) > 0) {
  939. $sql .= " ORDER BY ";
  940. foreach ($options['order_by'] as $field => $dir) {
  941. $sql .= "$field $dir, ";
  942. }
  943. $sql = drupal_substr($sql, 0, -2); // get rid of the trailing ', '
  944. }
  945. // if the caller has requested the SQL rather than the results...
  946. // which happens in the case of wanting to use the Drupal pager, then do so
  947. if ($options['return_sql'] == TRUE) {
  948. return array('sql' => $sql, 'args' => $args);
  949. }
  950. if (array_key_exists('limit', $pager)) {
  951. $resource = chado_pager_query($sql, $pager['limit'], $pager['element'], NULL, $args);
  952. }
  953. else {
  954. $resource = chado_query($sql, $args);
  955. }
  956. // format results into an array
  957. $results = array();
  958. foreach ($resource as $r) {
  959. $results[] = $r;
  960. }
  961. if ($options['has_record']) {
  962. return count($results);
  963. }
  964. return $results;
  965. }
  966. /**
  967. * Gets the value of a foreign key relationship
  968. *
  969. * This function is used by tripal_core_chado_select, tripal_core_chado_insert,
  970. * and tripal_core_chado_update to iterate through the associate array of
  971. * values that gets passed to each of those routines. The values array
  972. * is nested where foreign key contraints are used to specify a value that. See
  973. * documentation for any of those functions for further information.
  974. *
  975. * @param $table_desc
  976. * A table description for the table with the foreign key relationship to be identified generated by
  977. * hook_chado_<table name>_schema()
  978. * @param $field
  979. * The field in the table that is the foreign key.
  980. * @param $values
  981. * An associative array containing the values
  982. * @param $options
  983. * An associative array of additional options where the key is the option
  984. * and the value is the value of that option. These options are passed on to tripal_core_chado_select.
  985. *
  986. * Additional Options Include:
  987. * - case_insensitive_columns
  988. * An array of columns to do a case insensitive search on.
  989. * - regex_columns
  990. * An array of columns where the value passed in should be treated as a regular expression
  991. *
  992. * @return
  993. * A string containg the results of the foreign key lookup, or FALSE if failed.
  994. *
  995. * Example usage:
  996. * @code
  997. *
  998. * $values = array(
  999. * 'genus' => 'Citrus',
  1000. * 'species' => 'sinensis',
  1001. * );
  1002. * $value = tripal_core_chado_get_foreign_key('feature', 'organism_id',$values);
  1003. *
  1004. * @endcode
  1005. * The above code selects a record from the feature table using the three fields
  1006. * that uniquely identify a feature. The $columns array simply lists the columns
  1007. * to select. The $values array is nested such that the organism is identified by
  1008. * way of the organism_id foreign key constraint by specifying the genus and
  1009. * species. The cvterm is also specified using its foreign key and the cv_id
  1010. * for the cvterm is nested as well.
  1011. *
  1012. * @ingroup tripal_chado_api
  1013. */
  1014. function tripal_core_chado_get_foreign_key($table_desc, $field, $values, $options = NULL) {
  1015. // set defaults for options. If we don't set defaults then
  1016. // we get memory leaks when we try to access the elements
  1017. if (!is_array($options)) {
  1018. $options = array();
  1019. }
  1020. if (!array_key_exists('case_insensitive_columns', $options)) {
  1021. $options['case_insensitive_columns'] = array();
  1022. }
  1023. if (!array_key_exists('regex_columns', $options)) {
  1024. $options['regex_columns'] = array();
  1025. }
  1026. // get the list of foreign keys for this table description and
  1027. // iterate through those until we find the one we're looking for
  1028. $fkeys = '';
  1029. if (array_key_exists('foreign keys', $table_desc)) {
  1030. $fkeys = $table_desc['foreign keys'];
  1031. }
  1032. if ($fkeys) {
  1033. foreach ($fkeys as $name => $def) {
  1034. if (is_array($def['table'])) {
  1035. //foreign key was described 2X
  1036. $message = "The foreign key " . $name . " was defined twice. Please check modules "
  1037. . "to determine if hook_chado_schema_<version>_" . $table_desc['table'] . "() was "
  1038. . "implemented and defined this foreign key when it wasn't supposed to. Modules "
  1039. . "this hook was implemented in: " . implode(', ',
  1040. module_implements("chado_" . $table_desc['table'] . "_schema")) . ".";
  1041. watchdog('tripal_core', $message);
  1042. drupal_set_message(check_plain($message), 'error');
  1043. continue;
  1044. }
  1045. $table = $def['table'];
  1046. $columns = $def['columns'];
  1047. // iterate through the columns of the foreign key relationship
  1048. foreach ($columns as $left => $right) {
  1049. // does the left column in the relationship match our field?
  1050. if (strcmp($field, $left) == 0) {
  1051. // the column name of the foreign key matches the field we want
  1052. // so this is the right relationship. Now we want to select
  1053. $select_cols = array($right);
  1054. $result = tripal_core_chado_select($table, $select_cols, $values, $options);
  1055. $fields = array();
  1056. if ($result and count($result) > 0) {
  1057. foreach ($result as $obj) {
  1058. $fields[] = $obj->$right;
  1059. }
  1060. return $fields;
  1061. }
  1062. }
  1063. }
  1064. }
  1065. }
  1066. else {
  1067. // TODO: what do we do if we get to this point and we have a fk
  1068. // relationship expected but we don't have any definition for one in the
  1069. // table schema??
  1070. $version = tripal_core_get_chado_version(TRUE);
  1071. $message = t("There is no foreign key relationship defined for " . $field . " .
  1072. To define a foreign key relationship, determine the table this foreign
  1073. key referrs to (<foreign table>) and then implement
  1074. hook_chado_chado_schema_v<version>_<foreign table>(). See
  1075. tripal_feature_chado_v1_2_schema_feature for an example. Chado version: $version");
  1076. watchdog('tripal_core', $message);
  1077. drupal_set_message(check_plain($message), 'error');
  1078. }
  1079. return array();
  1080. }
  1081. /**
  1082. * Generates an object containing the full details of a record(s) in chado.
  1083. *
  1084. * This differs from the objects returned by tripal_core_chado_select in so far as all foreign key
  1085. * relationships have been followed meaning you have more complete details. Thus this function
  1086. * should be used whenever you need a full variable and tripal_core_chado_select should be used if
  1087. * you only case about a few columns.
  1088. *
  1089. * @param $table
  1090. * The name of the base table to generate a variable for
  1091. * @param $values
  1092. * A select values array that selects the records you want from the base table
  1093. * (this has the same form as tripal_core_chado_select)
  1094. * @param $base_options
  1095. * An array containing options for the base table. For example, an
  1096. * option of 'order_by' may be used to sort results in the base table
  1097. * if more than one are returned. The options must be compatible with
  1098. * the options accepted by the tripal_core_chado_select() function.
  1099. * Additionally, These options are available for this function:
  1100. * -return_array:
  1101. * can be provided to force the function to always return an array. Default
  1102. * behavior is to return a single record if only one record exists or to return
  1103. * an array if multiple records exist.
  1104. * - include_fk:
  1105. * an array of FK relationships to follow. By default, the
  1106. * tripal_core_chado_select function will follow all FK relationships but this
  1107. * may generate more queries then is desired slowing down this function call when
  1108. * there are lots of FK relationships to follow. Provide an array specifying the
  1109. * fields to include. For example, if expanding a property table (e.g. featureprop)
  1110. * and you want the CV and accession but do not want the DB the following
  1111. * array would work:
  1112. *
  1113. * $table_options = array(
  1114. * 'include_fk' => array(
  1115. * 'type_id' => array(
  1116. * 'cv_id' => 1,
  1117. * 'dbxref_id' => 1,
  1118. * )
  1119. * )
  1120. * );
  1121. *
  1122. * The above array will expand the 'type_id' of the property table but only
  1123. * further expand the cv_id and the dbxref_id and will go no further.
  1124. * - pager:
  1125. * Use this option if it is desired to return only a subset of results
  1126. * so that they may be shown within a Drupal-style pager. This should be
  1127. * an array with two keys: 'limit' and 'element'. The value of 'limit'
  1128. * should specify the number of records to return and 'element' is a
  1129. * unique integer to differentiate between pagers when more than one
  1130. * appear on a page. The 'element' should start with zero and increment by
  1131. * one for each pager. This only works when type is a 'table'.
  1132. * @return
  1133. * Either an object (if only one record was selected from the base table)
  1134. * or an array of objects (if more than one record was selected from the base table).
  1135. * If the option 'return_array' is provided the function always returns an array.
  1136. *
  1137. * Example Usage:
  1138. * @code
  1139. $values = array(
  1140. 'name' => 'Medtr4g030710'
  1141. );
  1142. $features = tripal_core_generate_chado_var('feature', $values);
  1143. * @endcode
  1144. * This will return an object if there is only one feature with the name Medtr4g030710 or it will
  1145. * return an array of feature objects if more than one feature has that name.
  1146. *
  1147. * Note to Module Designers: Fields can be excluded by default from these objects by implementing
  1148. * one of the following hooks:
  1149. * - hook_exclude_field_from_tablename_by_default (where tablename is the name of the table):
  1150. * This hook allows you to add fields to be excluded on a per table basis. Simply implement
  1151. * this hook to return an array of fields to be excluded. For example:
  1152. * @code
  1153. mymodule_exclude_field_from_feature_by_default() {
  1154. return array('residues' => TRUE);
  1155. }
  1156. * @endcode
  1157. * will ensure that feature.residues is ecluded from a feature object by default.
  1158. * - hook_exclude_type_by_default:
  1159. * This hook allows you to exclude fields from all tables that are of a given postgresql field
  1160. * type. Simply implement this hook to return an array of postgresql types mapped to criteria.
  1161. * Then all fields of that type where the criteria supplied returns TRUE will be excluded from
  1162. * any table. Tokens available in criteria are &gt;field_value&lt; and &gt;field_name&lt; . For example:
  1163. * @code
  1164. mymodule_exclude_type_by_default() {
  1165. return array('text' => 'length(&gt;field_value&lt; ) > 50');
  1166. }
  1167. * @endcode
  1168. * 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.
  1169. *
  1170. * @ingroup tripal_chado_api
  1171. */
  1172. function tripal_core_generate_chado_var($table, $values, $base_options = array()) {
  1173. $all = new stdClass();
  1174. $return_array = 0;
  1175. if (array_key_exists('return_array', $base_options)) {
  1176. $return_array = 1;
  1177. }
  1178. $include_fk = 0;
  1179. if (array_key_exists('include_fk', $base_options)) {
  1180. $include_fk = $base_options['include_fk'];
  1181. }
  1182. $pager = array();
  1183. if (array_key_exists('pager', $base_options)) {
  1184. $pager = $base_options['pager'];
  1185. }
  1186. // get description for the current table----------------------------------------------------------
  1187. $table_desc = tripal_core_get_chado_table_schema($table);
  1188. if (!$table_desc or count($table_desc) == 0) {
  1189. watchdog('tripal_core', "tripal_core_generate_chado_var: The table '%table' has not been defined. " .
  1190. "and cannot be expanded. If this is a custom table, please add it using the Tripal " .
  1191. "custom table interface.", array('%table' => $table), WATCHDOG_ERROR);
  1192. if ($return_array) {
  1193. return array();
  1194. }
  1195. return FALSE;
  1196. }
  1197. $table_primary_key = $table_desc['primary key'][0];
  1198. $table_columns = array_keys($table_desc['fields']);
  1199. // Expandable fields without value needed for criteria--------------------------------------------
  1200. $all->expandable_fields = array();
  1201. if ($table_desc['referring_tables']) {
  1202. $all->expandable_tables = $table_desc['referring_tables'];
  1203. }
  1204. else {
  1205. $all->expandable_tables = array();
  1206. }
  1207. $all->expandable_nodes = array();
  1208. /*
  1209. // Get fields to be removed by name.................................
  1210. $fields_to_remove = module_invoke_all('exclude_field_from_' . $table . '_by_default');
  1211. foreach ($fields_to_remove as $field_name => $criteria) {
  1212. //replace &gt;field_name&lt; with the current field name &
  1213. $criteria = preg_replace('/&gt;field_name&lt; /', addslashes($field_name), $criteria);
  1214. // if field_value needed we can't deal with this field yet
  1215. if (preg_match('/&gt;field_value&lt; /', $criteria)) {
  1216. break;
  1217. }
  1218. //if criteria then remove from query
  1219. // @coder-ignore: only module designers can populate $criteria -not security risk
  1220. $success = php_eval('<?php return ' . $criteria . '; ?>');
  1221. if ($success) {
  1222. unset($table_columns[array_search($field_name, $table_columns)]);
  1223. unset($fields_to_remove[$field_name]);
  1224. $all->expandable_fields[] = $table . '.' . $field_name;
  1225. }
  1226. }
  1227. //Get fields to be removed by type................................
  1228. $types_to_remove = module_invoke_all('exclude_type_by_default');
  1229. $field_types = array();
  1230. foreach ($table_desc['fields'] as $field_name => $field_array) {
  1231. $field_types[$field_array['type']][] = $field_name;
  1232. }
  1233. foreach ($types_to_remove as $field_type => $criteria) {
  1234. // if there are fields of that type to remove
  1235. if (is_array($field_types[$field_type])) {
  1236. //replace &gt;field_name&lt; with the current field name &
  1237. $criteria = preg_replace('/&gt;field_name&lt; /', addslashes($field_name), $criteria);
  1238. foreach ($field_types[$field_type] as $field_name) {
  1239. // if field_value needed we can't deal with this field yet
  1240. if (preg_match('/&gt;field_value&lt; /', $criteria)) {
  1241. $fields_to_remove[$field_name] = $criteria;
  1242. continue;
  1243. }
  1244. // if field_value needed we can't deal with this field yet
  1245. if (preg_match('/&gt;field_value&lt; /', $criteria)) {
  1246. break;
  1247. }
  1248. //if criteria then remove from query
  1249. // @coder-ignore: only module designers can populate $criteria -not security risk
  1250. $success = php_eval('<?php return ' . $criteria . '; ?>');
  1251. if ($success) {
  1252. unset($table_columns[array_search($field_name, $table_columns)]);
  1253. $all->expandable_fields[] = $table . '.' . $field_name;
  1254. }
  1255. } //end of foreach field of that type
  1256. }
  1257. } //end of foreach type to be removed
  1258. */
  1259. // get the values for the record in the current table---------------------------------------------
  1260. $results = tripal_core_chado_select($table, $table_columns, $values, $base_options);
  1261. if ($results) {
  1262. foreach ($results as $key => $object) {
  1263. // Add empty expandable_x arrays
  1264. $object->expandable_fields = $all->expandable_fields;
  1265. $object->expandable_tables = $all->expandable_tables;
  1266. $object->expandable_nodes = $all->expandable_nodes;
  1267. // add curent table
  1268. $object->tablename = $table;
  1269. // check if the current table maps to a node type-----------------------------------------------
  1270. // if this table is connected to a node there will be a chado_tablename table in drupal
  1271. if (db_table_exists('chado_' . $table)) {
  1272. // that has a foreign key to this one ($table_desc['primary key'][0]
  1273. // and to the node table (nid)
  1274. $sql = "
  1275. SELECT $table_primary_key, nid
  1276. FROM {chado_$table}
  1277. WHERE $table_primary_key = :$table_primary_key";
  1278. $mapping = db_query($sql, array(":$table_primary_key" => $object->{$table_primary_key}))->fetchObject();
  1279. if ($mapping->{$table_primary_key}) {
  1280. $object->nid = $mapping->nid;
  1281. $object->expandable_nodes[] = $table;
  1282. }
  1283. }
  1284. // remove any fields where criteria needs to be evalulated---------------------------------------
  1285. /* foreach ($fields_to_remove as $field_name => $criteria) {
  1286. if (!isset($object->{$field_name})) {
  1287. break;
  1288. }
  1289. $criteria = preg_replace('/&gt;field_value&lt; /', addslashes($object->{$field_name}), $criteria);
  1290. $success = php_eval('<?php return ' . $criteria . '; ?>');
  1291. if ($success) {
  1292. unset($object->{$field_name});
  1293. $object->expandable_fields[] = $table . '.' . $field_name;
  1294. }
  1295. }
  1296. */
  1297. // recursively follow foreign key relationships nesting objects as we go------------------------
  1298. if ($table_desc['foreign keys']) {
  1299. foreach ($table_desc['foreign keys'] as $foreign_key_array) {
  1300. $foreign_table = $foreign_key_array['table'];
  1301. foreach ($foreign_key_array['columns'] as $foreign_key => $primary_key) {
  1302. // Note: Foreign key is the field in the current table whereas primary_key is the field in
  1303. // the table referenced by the foreign key
  1304. //Dont do anything if the foreign key is empty
  1305. if (empty($object->{$foreign_key})) {
  1306. continue;
  1307. }
  1308. if ($include_fk) {
  1309. // don't recurse if the callee has supplied an $fk_include list and this
  1310. // FK table is not in the list.
  1311. if (is_array($include_fk) and !array_key_exists($foreign_key, $include_fk)) {
  1312. continue;
  1313. }
  1314. // if we have the option but it is not an array then we don't recurse any furutehr
  1315. if (!is_array($include_fk)) {
  1316. continue;
  1317. }
  1318. }
  1319. // get the record from the foreign table
  1320. $foreign_values = array($primary_key => $object->{$foreign_key});
  1321. $options = array();
  1322. if (is_array($include_fk)) {
  1323. $options['include_fk'] = $include_fk[$foreign_key];
  1324. }
  1325. $foreign_object = tripal_core_generate_chado_var($foreign_table, $foreign_values, $options);
  1326. // add the foreign record to the current object in a nested manner
  1327. $object->{$foreign_key} = $foreign_object;
  1328. // Flatten expandable_x arrays so only in the bottom object
  1329. if (is_array($object->{$foreign_key}->expandable_fields)) {
  1330. $object->expandable_fields = array_merge(
  1331. $object->expandable_fields,
  1332. $object->{$foreign_key}->expandable_fields
  1333. );
  1334. unset($object->{$foreign_key}->expandable_fields);
  1335. }
  1336. if (is_array($object->{$foreign_key}->expandable_tables)) {
  1337. $object->expandable_tables = array_merge(
  1338. $object->expandable_tables,
  1339. $object->{$foreign_key}->expandable_tables
  1340. );
  1341. unset($object->{$foreign_key}->expandable_tables);
  1342. }
  1343. if (is_array($object->{$foreign_key}->expandable_nodes)) {
  1344. $object->expandable_nodes = array_merge(
  1345. $object->expandable_nodes,
  1346. $object->{$foreign_key}->expandable_nodes
  1347. );
  1348. unset($object->{$foreign_key}->expandable_nodes);
  1349. }
  1350. }
  1351. }
  1352. $results[$key] = $object;
  1353. }
  1354. }
  1355. }
  1356. // convert the results into an array
  1357. $results_arr = array();
  1358. foreach ($results as $record) {
  1359. $results_arr[] = $record;
  1360. }
  1361. // check only one result returned
  1362. if (!$return_array) {
  1363. if (sizeof($results_arr) == 1) {
  1364. // add results to object
  1365. return $results_arr[0];
  1366. }
  1367. elseif (!empty($results_arr)) {
  1368. return $results_arr;
  1369. }
  1370. else {
  1371. // no results returned
  1372. }
  1373. }
  1374. // the caller has requested results are always returned as
  1375. // an array
  1376. else {
  1377. if (!$results_arr) {
  1378. return array();
  1379. }
  1380. else {
  1381. return $results_arr;
  1382. }
  1383. }
  1384. }
  1385. /**
  1386. * Retrieves fields/tables/nodes that were excluded by default from a variable and adds them
  1387. *
  1388. * This function exists to allow tripal_core_generate_chado_var() to excldue some
  1389. * fields/tables/nodes from the default form of a variable without making it extremely difficult for
  1390. * the tripal admin to get at these variables if he/she wants them.
  1391. *
  1392. * @param $object
  1393. * This must be an object generated using tripal_core_generate_chado_var()
  1394. * @param $type
  1395. * Must be one of 'field', 'table', 'node'. Indicates what is being expanded.
  1396. * @param $to_expand
  1397. * The name of the field/table/node to be expanded
  1398. * @param $table_options
  1399. * - order_by:
  1400. * An array containing options for the base table. For example, an
  1401. * option of 'order_by' may be used to sort results in the base table
  1402. * if more than one are returned. The options must be compatible with
  1403. * the options accepted by the tripal_core_chado_select() function.
  1404. * - return_array:
  1405. * Additionally, The option 'return_array' can be provided to force
  1406. * the function to expand tables as an array. Default behavior is to expand
  1407. * a table as single record if only one record exists or to expand as an array if
  1408. * multiple records exist.
  1409. * - include_fk:
  1410. * an array of FK relationships to follow. By default, the
  1411. * tripal_core_chado_select function will follow all FK relationships but this
  1412. * may generate more queries then is desired slowing down this function call when
  1413. * there are lots of FK relationships to follow. Provide an array specifying the
  1414. * fields to include. For example, if expanding a property table (e.g. featureprop)
  1415. * and you want the CV and accession but do not want the DB the following
  1416. * array would work:
  1417. * $table_options = array(
  1418. * 'include_fk' => array(
  1419. * 'type_id' => array(
  1420. * 'cv_id' => 1,
  1421. * 'dbxref_id' => 1,
  1422. * )
  1423. * )
  1424. * );
  1425. *
  1426. * The above array will expand the 'type_id' of the property table but only
  1427. * further expand the cv_id and the dbxref_id and will go no further.
  1428. * - pager:
  1429. * Use this option if it is desired to return only a subset of results
  1430. * so that they may be shown within a Drupal-style pager. This should be
  1431. * an array with two keys: 'limit' and 'element'. The value of 'limit'
  1432. * should specify the number of records to return and 'element' is a
  1433. * unique integer to differentiate between pagers when more than one
  1434. * appear on a page. The 'element' should start with zero and increment by
  1435. * one for each pager. This only works when type is a 'table'.
  1436. * @return
  1437. * A chado object supplemented with the field/table/node requested to be expanded.
  1438. * If the type is a table and it has already been expanded no changes is made to the
  1439. * returned object
  1440. *
  1441. * Example Usage:
  1442. * @code
  1443. // Get a chado object to be expanded
  1444. $values = array(
  1445. 'name' => 'Medtr4g030710'
  1446. );
  1447. $features = tripal_core_generate_chado_var('feature', $values);
  1448. // Expand the organism node
  1449. $feature = tripal_core_expand_chado_vars($feature, 'node', 'organism');
  1450. // Expand the feature.residues field
  1451. $feature = tripal_core_expand_chado_vars($feature, 'field', 'feature.residues');
  1452. // Expand the feature properties (featureprop table)
  1453. $feature = tripal_core_expand_chado_vars($feature, 'table', 'featureprop');
  1454. * @endcode
  1455. *
  1456. * @ingroup tripal_chado_api
  1457. */
  1458. function tripal_core_expand_chado_vars($object, $type, $to_expand, $table_options = array()) {
  1459. // make sure we have a value
  1460. if (!$object) {
  1461. watchdog('tripal_core', 'Cannot pass non array as argument, $object, to tripal_core_expand_chado_vars function.', array(), WATCHDOG_ERROR);
  1462. return $object;
  1463. }
  1464. // check to see if we are expanding an array of objects
  1465. if (is_array($object)) {
  1466. foreach ($object as $index => $o) {
  1467. $object[$index] = tripal_core_expand_chado_vars($o, $type, $to_expand);
  1468. }
  1469. return $object;
  1470. }
  1471. // get the base table name
  1472. $base_table = $object->tablename;
  1473. switch ($type) {
  1474. case "field": //--------------------------------------------------------------------------------
  1475. if (preg_match('/(\w+)\.(\w+)/', $to_expand, $matches)) {
  1476. $tablename = $matches[1];
  1477. $fieldname = $matches[2];
  1478. $table_desc = tripal_core_get_chado_table_schema($tablename);
  1479. $values = array();
  1480. foreach ($table_desc['primary key'] as $key) {
  1481. $values[$key] = $object->{$key};
  1482. }
  1483. if ($base_table == $tablename) {
  1484. //get the field
  1485. $results = tripal_core_chado_select($tablename, array($fieldname), $values);
  1486. $object->{$fieldname} = $results[0]->{$fieldname};
  1487. $object->expanded = $to_expand;
  1488. }
  1489. else {
  1490. //We need to recurse -the field is in a nested object
  1491. foreach ((array) $object as $field_name => $field_value) {
  1492. if (is_object($field_value)) {
  1493. $object->{$field_name} = tripal_core_expand_chado_vars(
  1494. $field_value,
  1495. 'field',
  1496. $to_expand
  1497. );
  1498. }
  1499. } //end of for each field in the current object
  1500. }
  1501. }
  1502. else {
  1503. watchdog('tripal_core', 'tripal_core_expand_chado_vars: Field (%field) not in the right format. " .
  1504. "It should be <tablename>.<fieldname>', WATCHDOG_ERROR);
  1505. }
  1506. break;
  1507. case "table": //--------------------------------------------------------------------------------
  1508. $foreign_table = $to_expand;
  1509. // don't expand the table it already is expanded
  1510. if (array_key_exists($foreign_table, $object)) {
  1511. return $object;
  1512. }
  1513. $foreign_table_desc = tripal_core_get_chado_table_schema($foreign_table);
  1514. // If it's connected to the base table via a FK constraint
  1515. if ($foreign_table_desc['foreign keys'][$base_table]) {
  1516. foreach ($foreign_table_desc['foreign keys'][$base_table]['columns'] as $left => $right) {
  1517. // if the FK value in the base table is not there then we can't expand it, so just skip it.
  1518. if (!$object->{$right}) {
  1519. continue;
  1520. }
  1521. // generate a new object for this table using the FK values in the base table.
  1522. // if a prepared statement is provided generate a new statement_name so that
  1523. // we don't conflict when we recurse.
  1524. $new_options = $table_options;
  1525. /*
  1526. if (array_key_exists('statement_name', $table_options)) {
  1527. $new_options['statement_name'] = "exp_" . $foreign_table . "_" . substr($left, 0, 2) . substr($right, 0, 2);
  1528. }
  1529. */
  1530. $foreign_object = tripal_core_generate_chado_var($foreign_table, array($left => $object->{$right}), $new_options);
  1531. // if the generation of the object was successful, update the base object to include it.
  1532. if ($foreign_object) {
  1533. // in the case where the foreign key relationships exists more
  1534. // than once with the same table we want to alter the array structure. rather than
  1535. // add the object with a key of the table name, we will add the FK field name in between
  1536. if (count($foreign_table_desc['foreign keys'][$base_table]['columns']) > 1) {
  1537. if (!is_object($object->{$foreign_table})) {
  1538. $object->{$foreign_table} = new stdClass();
  1539. }
  1540. $object->{$foreign_table}->{$left} = $foreign_object;
  1541. $object->expanded = $to_expand;
  1542. }
  1543. else {
  1544. if (!is_object($object->{$foreign_table})) {
  1545. $object->{$foreign_table} = new stdClass();
  1546. }
  1547. $object->{$foreign_table} = $foreign_object;
  1548. $object->expanded = $to_expand;
  1549. }
  1550. }
  1551. // if the object returned is NULL then handle that
  1552. else {
  1553. if (count($foreign_table_desc['foreign keys'][$base_table]['columns']) > 1) {
  1554. if (!is_object($object->{$foreign_table})) {
  1555. $object->{$foreign_table} = new stdClass();
  1556. }
  1557. $object->{$foreign_table}->{$left} = NULL;
  1558. }
  1559. else {
  1560. $object->{$foreign_table} = NULL;
  1561. }
  1562. }
  1563. }
  1564. }
  1565. // if the foreign table is not connected to the base table through a FK constraint
  1566. else {
  1567. // We need to recurse -the table has a relationship to one of the nested objects
  1568. $did_expansion = 0;
  1569. foreach ((array) $object as $field_name => $field_value) {
  1570. // if we have a nested object ->expand the table in it
  1571. if (is_object($field_value)) {
  1572. $did_expansion = 1;
  1573. $object->{$field_name} = tripal_core_expand_chado_vars($field_value, 'table', $foreign_table);
  1574. }
  1575. }
  1576. // if we did not expand this table we should return a message that the foreign table
  1577. // could not be expanded
  1578. if (!$did_expansion) {
  1579. watchdog('tripal_core', 'tripal_core_expand_chado_vars: Could not expand table, %table. It is ' .
  1580. 'not in a foreign key relationship with the base object nor with any other expanded table. ' .
  1581. 'Check the table definition to ensure that a proper foreign key relationship is present.',
  1582. array('%table' => $foreign_table), WATCHDOG_ERROR);
  1583. }
  1584. }
  1585. break;
  1586. case "node": //---------------------------------------------------------------------------------
  1587. //if the node to be expanded is for our base table, then just expand it
  1588. if ($object->tablename == $to_expand) {
  1589. $node = node_load($object->nid);
  1590. if ($node) {
  1591. $object->expanded = $to_expand;
  1592. $node->expandable_fields = $object->expandable_fields;
  1593. unset($object->expandable_fields);
  1594. $node->expandable_tables = $object->expandable_tables;
  1595. unset($object->expandable_tables);
  1596. $node->expandable_nodes = $object->expandable_nodes;
  1597. unset($object->expandable_nodes);
  1598. $node->{$base_table} = $object;
  1599. $object = $node;
  1600. }
  1601. else {
  1602. watchdog('tripal_core', 'tripal_core_expand_chado_vars: No node matches the nid (%nid) supplied.',
  1603. array('%nid' => $object->nid), WATCHDOG_ERROR);
  1604. } //end of if node
  1605. }
  1606. else {
  1607. //We need to recurse -the node to expand is one of the nested objects
  1608. foreach ((array) $object as $field_name => $field_value) {
  1609. if (is_object($field_value)) {
  1610. $object->{$field_name} = tripal_core_expand_chado_vars(
  1611. $field_value,
  1612. 'node',
  1613. $to_expand
  1614. );
  1615. }
  1616. } //end of for each field in the current object
  1617. }
  1618. break;
  1619. default:
  1620. watchdog('tripal_core', 'tripal_core_expand_chado_vars: Unrecognized type (%type). Should be one of "field", "table", "node".',
  1621. array('%type' => $type), WATCHDOG_ERROR);
  1622. return FALSE;
  1623. }
  1624. //move extended array downwards-------------------------------------------------------------------
  1625. if (!$object->expanded) {
  1626. //if there's no extended field then go hunting for it
  1627. foreach ( (array)$object as $field_name => $field_value) {
  1628. if (is_object($field_value)) {
  1629. if (isset($field_value->expanded)) {
  1630. $object->expanded = $field_value->expanded;
  1631. unset($field_value->expanded);
  1632. }
  1633. }
  1634. }
  1635. }
  1636. //try again becasue now we might have moved it down
  1637. if ($object->expanded) {
  1638. $expandable_name = 'expandable_' . $type . 's';
  1639. if ($object->{$expandable_name}) {
  1640. $key_to_remove = array_search($object->expanded, $object->{$expandable_name});
  1641. unset($object->{$expandable_name}[$key_to_remove]);
  1642. unset($object->expanded);
  1643. }
  1644. else {
  1645. // if there is an expandable array then we've reached the base object
  1646. // if we get here and don't have anything expanded then something went wrong
  1647. // watchdog(
  1648. // 'tripal_core',
  1649. // 'tripal_core_expand_chado_vars: Unable to expand the %type %to_expand',
  1650. // array('%type'=>$type, '%to_expand'=>$to_expand),
  1651. // WATCHDOG_ERROR
  1652. // );
  1653. } //end of it we've reached the base object
  1654. }
  1655. return $object;
  1656. }
  1657. /**
  1658. * Implements hook_exclude_type_by_default()
  1659. *
  1660. * This hooks allows fields of a specified type that match a specified criteria to be excluded by
  1661. * default from any table when tripal_core_generate_chado_var() is called. Keep in mind that if
  1662. * fields are excluded by default they can always be expanded at a later date using
  1663. * tripal_core_expand_chado_vars().
  1664. *
  1665. * Criteria are php strings that evaluate to either TRUE or FALSE. These strings are evaluated using
  1666. * drupal_eval() which suppresses syntax errors and throws watchdog entries of type php. There are
  1667. * also watchdog entries of type tripal_core stating the exact criteria evaluated. Criteria can
  1668. * contain the following tokens:
  1669. * - &gt;field_name&lt;
  1670. * Replaced by the name of the field to be excluded
  1671. * - &gt;field_value&lt;
  1672. * Replaced by the value of the field in the current record
  1673. * Also keep in mind that if your criteria doesn't contain the &gt;field_value&lt; token then it will be
  1674. * evaluated before the query is executed and if the field is excluded it won't be included in the
  1675. * query.
  1676. *
  1677. * @return
  1678. * An array of type => criteria where the type is excluded if the criteria evaluates to TRUE
  1679. *
  1680. * @ingroup tripal_chado_api
  1681. */
  1682. function tripal_core_exclude_type_by_default() {
  1683. return array('text' => 'strlen("&gt;field_value&lt; ") > 100');
  1684. }
  1685. /**
  1686. * Implements hook_exclude_field_from_<tablename>_by_default()
  1687. *
  1688. * This hooks allows fields from a specified table that match a specified criteria to be excluded by
  1689. * default from any table when tripal_core_generate_chado_var() is called. Keep in mind that if
  1690. * fields are excluded by default they can always be expanded at a later date using
  1691. * tripal_core_expand_chado_vars().
  1692. *
  1693. * Criteria are php strings that evaluate to either TRUE or FALSE. These strings are evaluated using
  1694. * drupal_eval() which suppresses syntax errors and throws watchdog entries of type php. There are
  1695. * also watchdog entries of type tripal_core stating the exact criteria evaluated. Criteria can
  1696. * contain the following tokens:
  1697. * - &gt;field_name&lt;
  1698. * Replaced by the name of the field to be excluded
  1699. * - &gt;field_value&lt;
  1700. * Replaced by the value of the field in the current record
  1701. * Also keep in mind that if your criteria doesn't contain the &gt;field_value&lt; token then it will be
  1702. * evaluated before the query is executed and if the field is excluded it won't be included in the
  1703. * query.
  1704. *
  1705. * @return
  1706. * An array of type => criteria where the type is excluded if the criteria evaluates to TRUE
  1707. *
  1708. * @ingroup tripal_chado_api
  1709. */
  1710. function tripal_core_exclude_field_from_feature_by_default() {
  1711. return array();
  1712. }
  1713. /**
  1714. * Use this function instead of pager_query() when selecting a
  1715. * subset of records from a Chado table.
  1716. *
  1717. * @param $query
  1718. * The SQL statement to execute, this is followed by a variable number of args
  1719. * used as substitution values in the SQL statement.
  1720. * @param $limit
  1721. * The number of query results to display per page.
  1722. * @param $element
  1723. * An optional integer to distinguish between multiple pagers on one page.
  1724. * @param $count_query
  1725. * An SQL query used to count matching records.
  1726. *
  1727. * @returns
  1728. * A database query result resource or FALSE if the query was not
  1729. * executed correctly
  1730. *
  1731. * @ingroup tripal_chado_api
  1732. */
  1733. function chado_pager_query($query, $limit, $element, $count_query) {
  1734. // The following code is almost an exact duplicate of the
  1735. // Drupal pager_query function. However, substitions have
  1736. // been made to call chado_query rather than db_query
  1737. global $pager_page_array, $pager_total, $pager_total_items;
  1738. $page = isset($_GET['page']) ? $_GET['page'] : '';
  1739. // get the SQL query arguments that get substituted into modifiers later.
  1740. $args = func_get_args();
  1741. $args = array_slice($args, 4);
  1742. // Alternative syntax for '...'
  1743. if (isset($args[0]) && is_array($args[0])) {
  1744. $args = $args[0];
  1745. }
  1746. // Construct a count query if none was given.
  1747. if (!isset($count_query)) {
  1748. $count_query = preg_replace(array('/SELECT.*?FROM /As', '/ORDER BY .*/'), array('SELECT COUNT(*) FROM ', ''), $query);
  1749. }
  1750. // Convert comma-separated $page to an array, used by other functions.
  1751. $pager_page_array = explode(',', $page);
  1752. // We calculate the total of pages as ceil(items / limit).
  1753. $pager_total_items[$element] = db_result(chado_query($count_query, $args));
  1754. $pager_total[$element] = ceil($pager_total_items[$element] / $limit);
  1755. $pager_page_array[$element] = max(0, min((int) $pager_page_array[$element], ((int) $pager_total[$element]) - 1));
  1756. return chado_query_range($query, $args, $pager_page_array[$element] * $limit, $limit);
  1757. }
  1758. /**
  1759. * Use this function instead of db_query_range().
  1760. *
  1761. * @param $sql
  1762. * The SQL statement to execute, this is followed by a variable number of args
  1763. * used as substitution values in the SQL statement.
  1764. * @param $args
  1765. * The SQL arguments
  1766. * @param $from
  1767. * The first result row to return..
  1768. * @param $count
  1769. * The maximum number of result rows to return.
  1770. *
  1771. * @returns
  1772. * A database query result resource or FALSE if the query was not
  1773. * executed correctly
  1774. *
  1775. * @ingroup tripal_chado_api
  1776. */
  1777. function chado_query_range($query, $args, $from, $count) {
  1778. $query .= ' LIMIT ' . (int) $count . ' OFFSET ' . (int) $from;
  1779. return chado_query($query, $args);
  1780. }
  1781. /**
  1782. * Use this function instead of db_query() to avoid switching databases
  1783. * when making query to the chado database
  1784. *
  1785. * Will use a chado persistent connection if it already exists
  1786. *
  1787. * @param $sql
  1788. * The sql statement to execute
  1789. *
  1790. * @param $args
  1791. * The array of arguments, with the same structure as passed to
  1792. * the db_query() function of Drupal.
  1793. *
  1794. * @return
  1795. * DatabaseStatementInterface A prepared statement object, already executed.
  1796. *
  1797. * @ingroup tripal_chado_api
  1798. */
  1799. function chado_query($sql, $args = array()) {
  1800. $is_local = tripal_core_is_chado_local();
  1801. if (!is_array($args)) {
  1802. watchdog('tripal_core', 'Need to pass an array to chado_query, "%value" passed instead. Query: %query', array('%value' => $args, '%query' => $sql), WATCHDOG_ERROR);
  1803. $args = array($args);
  1804. }
  1805. // if Chado is local to the database then prefix the Chado table
  1806. // names with 'chado'.
  1807. if ($is_local) {
  1808. $sql = preg_replace('/\n/', '', $sql); // remove carriage returns
  1809. $sql = preg_replace('/\{(.*?)\}/', 'chado.$1', $sql);
  1810. $results = db_query($sql, $args);
  1811. }
  1812. // if Chado is not local to the Drupal database then we have to
  1813. // switch to another database
  1814. else {
  1815. $previous_db = tripal_db_set_active('chado') ;
  1816. $results = db_query($sql);
  1817. tripal_db_set_active($previous_db);
  1818. }
  1819. return $results;
  1820. }
  1821. /**
  1822. * Get chado id for a node. E.g, if you want to get 'analysis_id' from the
  1823. * 'analysis' table for a synced 'chado_analysis' node, (the same for
  1824. * organisms and features):
  1825. * $analysis_id = chado_get_id_for_node ('analysis', $node->nid)
  1826. * $organism_id = chado_get_id_for_node ('organism', $node->nid)
  1827. * $feature_id = chado_get_id_for_node ('feature', $node->nid)
  1828. *
  1829. * @param $table
  1830. * @param $nid
  1831. *
  1832. * @ingroup tripal_chado_api
  1833. */
  1834. function chado_get_id_for_node($table, $nid) {
  1835. $sql = "SELECT " . $table . "_id as id FROM {chado_$table} WHERE nid = :nid";
  1836. $result = db_query($sql, array(':nid' => $nid))->fetchObject();
  1837. return $result->id;
  1838. }
  1839. /**
  1840. * Get node id for a chado feature/organism/analysis. E.g, if you want to
  1841. * get the node id for an analysis, use:
  1842. * $nid = chado_get_node_id ('analysis', $analysis_id)
  1843. * Likewise,
  1844. * $nid = chado_get_node_id ('organism', $organism_id)
  1845. * $nid = chado_get_node_id ('feature', $feature_id)
  1846. *
  1847. * @ingroup tripal_chado_api
  1848. */
  1849. function chado_get_node_id($table, $id) {
  1850. $sql = "SELECT nid FROM {chado_$table} WHERE " . $table . "_id = :" . $table . "_id";
  1851. $result = db_query($sql, array(":" . $table . "_id" => $id))->fetchObject();
  1852. return $results->nid;
  1853. }
  1854. /**
  1855. * Retrieve a property for a given base table record
  1856. *
  1857. * @param $basetable
  1858. * The base table for which the property should be retrieved. Thus to retrieve a property
  1859. * for a feature the basetable=feature and property is retrieved from featureprop
  1860. * @param $record_id
  1861. * The foriegn key field of the base table. This should be in integer.
  1862. * @param $property
  1863. * The cvterm name describing the type of properties to be retrieved
  1864. * @param $cv_name
  1865. * The name of the cv that the above cvterm is part of
  1866. *
  1867. * @return
  1868. * An array in the same format as that generated by the function
  1869. * tripal_core_generate_chado_var(). If only one record is returned it
  1870. * is a single object. If more than one record is returned then it is an array
  1871. * of objects
  1872. *
  1873. * @ingroup tripal_chado_api
  1874. */
  1875. function tripal_core_get_property($basetable, $record_id, $property, $cv_name) {
  1876. // get the foreign key for this property table
  1877. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  1878. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1879. // construct the array of values to be selected
  1880. $values = array(
  1881. $fkcol => $record_id,
  1882. 'type_id' => array(
  1883. 'cv_id' => array(
  1884. 'name' => $cv_name,
  1885. ),
  1886. 'name' => $property,
  1887. 'is_obsolete' => 0
  1888. ),
  1889. );
  1890. $results = tripal_core_generate_chado_var($basetable . 'prop', $values);
  1891. if ($results) {
  1892. $results = tripal_core_expand_chado_vars($results, 'field', $basetable . 'prop.value');
  1893. }
  1894. return $results;
  1895. }
  1896. /**
  1897. * Insert a property for a given base table. By default if the property already
  1898. * exists a new property is added with the next available rank. If
  1899. * $update_if_present argument is specified then the record will be updated if it
  1900. * exists rather than adding a new property.
  1901. *
  1902. * @param $basetable
  1903. * The base table for which the property should be inserted. Thus to insert a property
  1904. * for a feature the basetable=feature and property is inserted into featureprop
  1905. * @param $record_id
  1906. * The foriegn key value of the base table. This should be in integer.
  1907. * @param $property
  1908. * The cvterm name describing the type of properties to be inserted
  1909. * @param $cv_name
  1910. * The name of the cv that the above cvterm is part of
  1911. * @param $value
  1912. * The value of the property to be inserted (can be empty)
  1913. * @param $update_if_present
  1914. * A boolean indicating whether an existing record should be updated. If the
  1915. * property already exists and this value is not specified or is zero then
  1916. * a new property will be added with the next largest rank.
  1917. *
  1918. * @return
  1919. * Return True on Insert/Update and False otherwise
  1920. *
  1921. * @ingroup tripal_chado_api
  1922. */
  1923. function tripal_core_insert_property($basetable, $record_id, $property,
  1924. $cv_name, $value, $update_if_present = 0) {
  1925. // first see if the property already exists, if the user want's to update
  1926. // then we can do that, but otherwise we want to increment the rank and
  1927. // insert
  1928. $props = tripal_core_get_property($basetable, $record_id, $property, $cv_name);
  1929. if (!is_array($props) and $props) {
  1930. $props = array($props);
  1931. }
  1932. $rank = 0;
  1933. if (count($props) > 0) {
  1934. if ($update_if_present) {
  1935. return tripal_core_update_property($basetable, $record_id, $property, $cv_name, $value);
  1936. }
  1937. else {
  1938. // iterate through the properties returned and check to see if the
  1939. // property with this value already exists if not, get the largest rank
  1940. // and insert the same property but with this new value
  1941. foreach ($props as $p) {
  1942. if ($p->rank > $rank) {
  1943. $rank = $p->rank;
  1944. }
  1945. if (strcmp($p->value, $value) == 0) {
  1946. return TRUE;
  1947. }
  1948. }
  1949. // now add 1 to the rank
  1950. $rank++;
  1951. }
  1952. }
  1953. // make sure the cvterm exists. Otherwise we'll get an error with
  1954. // prepared statements not matching
  1955. $values = array(
  1956. 'cv_id' => array(
  1957. 'name' => $cv_name,
  1958. ),
  1959. 'name' => $property,
  1960. );
  1961. $options = array('statement_name' => 'sel_cvterm_cv');
  1962. $term = tripal_core_chado_select('cvterm', array('cvterm_id'), $values, $options);
  1963. if (!$term or count($term) == 0) {
  1964. watchdog('tripal_core', "Cannot find property '%prop_name'.",
  1965. array('%prop_name' => $property), WATCHDOG_ERROR);
  1966. return FALSE;
  1967. }
  1968. // get the foreign key for this property table
  1969. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  1970. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1971. // construct the array of values to be inserted
  1972. $values = array(
  1973. $fkcol => $record_id,
  1974. 'type_id' => array(
  1975. 'cv_id' => array(
  1976. 'name' => $cv_name,
  1977. ),
  1978. 'name' => $property,
  1979. ),
  1980. 'value' => $value,
  1981. 'rank' => $rank,
  1982. );
  1983. $options = array('statement_name' => 'ins_' . $basetable . 'prop_' . substr($fkcol, 0, 2) . 'tyvara');
  1984. $result = tripal_core_chado_insert($basetable . 'prop', $values, $options);
  1985. return $result;
  1986. }
  1987. /**
  1988. * Update a property for a given base table record and property name. This
  1989. * function should be used only if one record of the property will be present.
  1990. * If the property name can have multiple entries (with increasing rank) then
  1991. * use the function named tripal_core_update_property_by_id
  1992. *
  1993. * @param $basetable
  1994. * The base table for which the property should be updated. The property table
  1995. * is constructed using a combination of the base table name and the suffix
  1996. * 'prop' (e.g. basetable = feature then property tabie is featureprop).
  1997. * @param $record_id
  1998. * The foreign key of the basetable to update a property for. This should be in integer.
  1999. * For example, if the basetable is 'feature' then the $record_id should be the feature_id
  2000. * @param $property
  2001. * The cvterm name of property to be updated
  2002. * @param $cv_name
  2003. * The name of the cv that the above cvterm is part of
  2004. * @param $value
  2005. * The value of the property to be inserted (can be empty)
  2006. * @param $insert_if_missing
  2007. * A boolean indicating whether a record should be inserted if one doesn't exist to update
  2008. *
  2009. * Note: The property to be updated is select via the unique combination of $record_id and
  2010. * $property and then it is updated with the supplied value
  2011. *
  2012. * @return
  2013. * Return True on Update/Insert and False otherwise
  2014. *
  2015. * @ingroup tripal_chado_api
  2016. */
  2017. function tripal_core_update_property($basetable, $record_id, $property,
  2018. $cv_name, $value, $insert_if_missing = 0) {
  2019. // first see if the property is missing (we can't update a missing property
  2020. $prop = tripal_core_get_property($basetable, $record_id, $property, $cv_name);
  2021. if (count($prop)==0) {
  2022. if ($insert_if_missing) {
  2023. return tripal_core_insert_property($basetable, $record_id, $property, $cv_name, $value);
  2024. }
  2025. else {
  2026. return FALSE;
  2027. }
  2028. }
  2029. // get the foreign key for this property table
  2030. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  2031. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  2032. // construct the array that will match the exact record to update
  2033. $match = array(
  2034. $fkcol => $record_id,
  2035. 'type_id' => array(
  2036. 'cv_id' => array(
  2037. 'name' => $cv_name,
  2038. ),
  2039. 'name' => $property,
  2040. ),
  2041. );
  2042. // construct the array of values to be updated
  2043. $values = array(
  2044. 'value' => $value,
  2045. );
  2046. return tripal_core_chado_update($basetable . 'prop', $match, $values);
  2047. }
  2048. /**
  2049. * Update a property for a given base table record. This function should be
  2050. * used if multiple records of the same property will be present. Also, use this
  2051. * function to change the property name of an existing property.
  2052. *
  2053. * @param $basetable
  2054. * The base table for which the property should be updated. The property table
  2055. * is constructed using a combination of the base table name and the suffix
  2056. * 'prop' (e.g. basetable = feature then property tabie is featureprop).
  2057. * @param $record_id
  2058. * The primary key of the base table. This should be in integer.
  2059. * For example, if the basetable is 'feature' then the $record_id should be the featureprop_id
  2060. * @param $property
  2061. * The cvterm name of property to be updated
  2062. * @param $cv_name
  2063. * The name of the cv that the above cvterm is part of
  2064. * @param $value
  2065. * The value of the property to be inserted (can be empty)
  2066. *
  2067. * @return
  2068. * Return True on Update/Insert and False otherwise
  2069. *
  2070. * @ingroup tripal_chado_api
  2071. */
  2072. function tripal_core_update_property_by_id($basetable, $record_id, $property,
  2073. $cv_name, $value) {
  2074. // get the primary key for this property table
  2075. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  2076. $pkcol = $table_desc['primary key'][0];
  2077. // construct the array that will match the exact record to update
  2078. $match = array(
  2079. $pkcol => $record_id,
  2080. );
  2081. // construct the array of values to be updated
  2082. $values = array(
  2083. 'type_id' => array(
  2084. 'cv_id' => array(
  2085. 'name' => $cv_name,
  2086. ),
  2087. 'name' => $property,
  2088. ),
  2089. 'value' => $value,
  2090. );
  2091. return tripal_core_chado_update($basetable . 'prop', $match, $values);
  2092. }
  2093. /**
  2094. * Deletes a property for a given base table record using the property name
  2095. *
  2096. * @param $basetable
  2097. * The base table for which the property should be deleted. Thus to deleted a property
  2098. * for a feature the basetable=feature and property is deleted from featureprop
  2099. * @param $record_id
  2100. * The primary key of the basetable to delete a property for. This should be in integer.
  2101. * @param $property
  2102. * The cvterm name describing the type of property to be deleted
  2103. * @param $cv_name
  2104. * The name of the cv that the above cvterm is part of
  2105. *
  2106. * Note: The property to be deleted is select via the unique combination of $record_id and $property
  2107. *
  2108. * @return
  2109. * Return True on Delete and False otherwise
  2110. *
  2111. * @ingroup tripal_chado_api
  2112. */
  2113. function tripal_core_delete_property($basetable, $record_id, $property, $cv_name) {
  2114. // get the foreign key for this property table
  2115. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  2116. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  2117. // construct the array that will match the exact record to update
  2118. $match = array(
  2119. $fkcol => $record_id,
  2120. 'type_id' => array(
  2121. 'cv_id' => array(
  2122. 'name' => $cv_name,
  2123. ),
  2124. 'name' => $property,
  2125. ),
  2126. );
  2127. return tripal_core_chado_delete($basetable . 'prop', $match);
  2128. }
  2129. /**
  2130. * Deletes a property using the property ID
  2131. *
  2132. * @param $basetable
  2133. * The base table for which the property should be deleted. Thus to deleted a property
  2134. * for a feature the basetable=feature and property is deleted from featureprop
  2135. * @param $record_id
  2136. * The primary key of the basetable to delete a property for. This should be in integer.
  2137. *
  2138. * @return
  2139. * Return True on Delete and False otherwise
  2140. *
  2141. * @ingroup tripal_chado_api
  2142. */
  2143. function tripal_core_delete_property_by_id($basetable, $record_id) {
  2144. // get the foreign key for this property table
  2145. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  2146. $pkcol = $table_desc['primary key'][0];
  2147. // construct the array that will match the exact record to update
  2148. $match = array(
  2149. $pkcol => $record_id,
  2150. );
  2151. return tripal_core_chado_delete($basetable . 'prop', $match);
  2152. }
  2153. /**
  2154. * Start a transaction block. Ensures the use of a persistent chado connection
  2155. */
  2156. function tripal_db_start_transaction() {
  2157. /* $connection = tripal_db_persistent_chado();
  2158. if ($connection) {
  2159. chado_query("BEGIN");
  2160. return $connection;
  2161. }
  2162. return FALSE;
  2163. */
  2164. }
  2165. /**
  2166. * Set a savepoint to roll the current transaction back to if an error is encountered
  2167. */
  2168. function tripal_db_set_savepoint_transaction($savepoint, $release = FALSE) {
  2169. // Postgresql requires a savepoint of the same name to be unset before re-use
  2170. if ($release) {
  2171. chado_query("RELEASE SAVEPOINT :savepoint", array(':savepoint' => $savepoint));
  2172. }
  2173. chado_query("SAVEPOINT :savepoint", array(':savepoint' => $savepoint));
  2174. }
  2175. /**
  2176. * A simple function to commit a database transaction
  2177. *
  2178. * @return nothing
  2179. */
  2180. function tripal_db_commit_transaction() {
  2181. chado_query("COMMIT");
  2182. }
  2183. /**
  2184. * Rollback changes.
  2185. *
  2186. * If $savepoint is NULL then rollback to the beginning of the transaction,
  2187. * Otherwise, rollback to the point at which the named $savepoint was created
  2188. *
  2189. * @param $savepoint
  2190. * The name of the saved point in the transaction to rollback to
  2191. *
  2192. * @param $commit
  2193. * The transcation will only be committed if this value is TRUE. The
  2194. * default is TRUE.
  2195. *
  2196. * @return nothing
  2197. */
  2198. function tripal_db_rollback_transaction($savepoint = NULL, $commit = TRUE) {
  2199. if ($savepoint) {
  2200. chado_query("ROLLBACK TO SAVEPOINT :savepoint", array(':savepoint' => $savepoint));
  2201. }
  2202. else {
  2203. chado_query("ROLLBACK");
  2204. }
  2205. if ($commit) {
  2206. tripal_db_commit_transaction();
  2207. }
  2208. }
  2209. /**
  2210. * Retrieves the schema in an array for the specified custom table.
  2211. *
  2212. * @param $table
  2213. * The name of the table to create.
  2214. *
  2215. * @return
  2216. * A Drupal-style Schema API array definition of the table. Returns
  2217. * FALSE on failure.
  2218. *
  2219. * @ingroup tripal_core_api
  2220. */
  2221. function tripal_get_chado_custom_schema($table) {
  2222. $sql = "SELECT schema FROM {tripal_custom_tables} WHERE table_name = :table_name";
  2223. $results = db_query($sql, array(':table_name' => $table));
  2224. $custom = $results->fetchObject();
  2225. if (!$custom) {
  2226. return FALSE;
  2227. }
  2228. else {
  2229. return unserialize($custom->schema);
  2230. }
  2231. }
  2232. /**
  2233. * Check that any given Chado table exists. This function
  2234. * is necessary because Drupa's db_table_exists function
  2235. * hardcodes the 'public'
  2236. *
  2237. * @return
  2238. * TRUE/FALSE depending upon whether it exists
  2239. */
  2240. function chado_table_exists($table) {
  2241. global $databases;
  2242. $default_db = $databases['default']['default']['database'];
  2243. $sql = "
  2244. SELECT 1
  2245. FROM information_schema.tables
  2246. WHERE
  2247. table_name = :table_name AND
  2248. table_schema = 'chado' AND
  2249. table_catalog = '$default_db'
  2250. ";
  2251. $results = db_query($sql, array(':table_name' => $table));
  2252. $exists = $results->fetchObject();
  2253. if (!$exists) {
  2254. return FALSE;
  2255. }
  2256. return TRUE;
  2257. }
  2258. /**
  2259. * Check that the Chado schema exists within the local database
  2260. *
  2261. * @return
  2262. * TRUE/FALSE depending upon whether it exists
  2263. */
  2264. function tripal_core_chado_schema_exists() {
  2265. // This is postgresql-specific code to check the existence of the chado schema
  2266. // @coder-ignore: acting on pg_catalog schema rather then drupal schema therefore, table prefixing does not apply
  2267. $sql = "
  2268. SELECT nspname
  2269. FROM pg_catalog.pg_namespace
  2270. WHERE nspname = 'chado'
  2271. ";
  2272. $results = db_query($sql);
  2273. $name = $results->fetchObject();
  2274. if ($name) {
  2275. return TRUE;
  2276. }
  2277. else {
  2278. return FALSE;
  2279. }
  2280. }
  2281. /**
  2282. * Check that any given schema exists
  2283. *
  2284. * @param $schema
  2285. * The name of the schema to check the existence of
  2286. *
  2287. * @return
  2288. * TRUE/FALSE depending upon whether or not the schema exists
  2289. *
  2290. * @ingroup tripal_chado_api
  2291. */
  2292. function tripal_core_schema_exists($schema) {
  2293. // check that the chado schema now exists
  2294. $sql = "
  2295. SELECT nspname
  2296. FROM pg_namespace
  2297. WHERE
  2298. has_schema_privilege(nspname, 'USAGE') AND
  2299. nspname = :nspname
  2300. ORDER BY nspname
  2301. ";
  2302. $results = db_query($sql, array(':nspname' => $schema));
  2303. $name = $results->fetchObject();
  2304. if (strcmp($name->nspname, $schema) != 0) {
  2305. return FALSE;
  2306. }
  2307. return TRUE;
  2308. }
  2309. /**
  2310. * Retrieves the list tables in the Chado schema. By default it only retursn
  2311. * the default Chado tables, but may also return custom tables added to the
  2312. * Chado schema as well.
  2313. *
  2314. * @param $include_custom
  2315. * Optional. Set as TRUE to include any custom tables created in the
  2316. * Chado schema. Custom tables are added to Chado using the
  2317. * tripal_core_chado_create_table() function.
  2318. *
  2319. * @returns
  2320. * An associative array where the key and value pairs are the Chado table names.
  2321. *
  2322. * @ingroup tripal_core_api
  2323. */
  2324. function tripal_core_get_chado_tables($include_custom = NULL) {
  2325. // first get the chado version that is installed
  2326. $v = tripal_core_get_chado_version();
  2327. $tables = array();
  2328. if ($v == '1.2') {
  2329. $tables_v1_2 = tripal_core_chado_get_v1_2_tables();
  2330. foreach ($tables_v1_2 as $table) {
  2331. $tables[$table] = $table;
  2332. }
  2333. }
  2334. if ($v == '1.11' or $v == '1.11 or older') {
  2335. $tables_v1_11 = tripal_core_chado_get_v1_11_tables();
  2336. foreach ($tables_v1_11 as $table) {
  2337. $tables[$table] = $table;
  2338. }
  2339. }
  2340. // now add in the custom tables too if requested
  2341. if ($include_custom) {
  2342. $sql = "SELECT table_name FROM {tripal_custom_tables}";
  2343. $resource = db_query($sql);
  2344. foreach ($resource as $r) {
  2345. $tables[$r->table_name] = $r->table_name;
  2346. }
  2347. }
  2348. asort($tables);
  2349. return $tables;
  2350. }
  2351. /**
  2352. * Sets a Drupal variable with the current version of Chado. This variable
  2353. * can then be queried later using the tripal_core_get_chado_Version
  2354. *
  2355. * @returns
  2356. * The version of Chado
  2357. *
  2358. * @ingroup tripal_core_api
  2359. */
  2360. function tripal_core_set_chado_version() {
  2361. global $databases;
  2362. $is_local = 0;
  2363. // check that Chado is installed if not return 'uninstalled as the version'
  2364. $chado_exists = tripal_core_chado_schema_exists();
  2365. if (!$chado_exists) {
  2366. // if it's not in the drupal database check to see if it's specified in the $db_url
  2367. // in the settings.php
  2368. if (!array_key_exists('chado', $databases)) {
  2369. // if it's not in the drupal database or specified in the $db_url then
  2370. // return uninstalled as the version
  2371. return 'not installed';
  2372. }
  2373. $previous_db = tripal_db_set_active('chado');
  2374. $prop_exists = db_table_exists('chadoprop');
  2375. tripal_db_set_active($previous_db);
  2376. }
  2377. else {
  2378. $is_local = 1;
  2379. $prop_exists = db_table_exists('chado.chadoprop');
  2380. }
  2381. // if the table doesn't exist then we don't know what version but we know
  2382. // it must be 1.11 or older.
  2383. if (!$prop_exists) {
  2384. return "1.11 or older";
  2385. }
  2386. $sql = "
  2387. SELECT value
  2388. FROM {chadoprop} CP
  2389. INNER JOIN {cvterm} CVT on CVT.cvterm_id = CP.type_id
  2390. INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
  2391. WHERE CV.name = 'chado_properties' and CVT.name = 'version'
  2392. ";
  2393. if (!$is_local) {
  2394. $previous_db = tripal_db_set_active('chado');
  2395. $results = db_query($sql);
  2396. tripal_db_set_active($previous_db);
  2397. }
  2398. else {
  2399. $results = chado_query($sql);
  2400. }
  2401. $v = $results->fetchObject();
  2402. // if we don't have a version in the chadoprop table then it must be
  2403. // v1.11 or older
  2404. if (!$v) {
  2405. variable_set('chado_version', "1.11 or older");
  2406. return "1.11 or older";
  2407. }
  2408. variable_set('chado_version', $v->value);
  2409. return $v->value;
  2410. }
  2411. /**
  2412. * Returns the version number of the currently installed Chado instance.
  2413. * It can return the real or effective version.
  2414. *
  2415. * @param $exact
  2416. * Set this argument to 1 to retrieve the exact version that is installed.
  2417. * Otherwise, this function will set the version to the nearest 'tenth'.
  2418. * Chado versioning numbers in the hundreds represent changes to the
  2419. * software and not the schema. Changes in the tenth's represent changes
  2420. * in the schema.
  2421. *
  2422. * @param $warn_if_unsupported
  2423. * If the currently installed version of Chado is not supported by Tripal
  2424. * the generatea a Drupal warning.
  2425. *
  2426. * @returns
  2427. * The version of Chado
  2428. *
  2429. * @ingroup tripal_core_api
  2430. */
  2431. function tripal_core_get_chado_version($exact = FALSE, $warn_if_unsupported = FALSE) {
  2432. // first get the chado version that is installed
  2433. // $exact_version = variable_get('chado_version', '');
  2434. // if (!$exact_version) {
  2435. $exact_version = tripal_core_set_chado_version();
  2436. // }
  2437. // Tripal only supports v1.11 or newer.. really this is the same as v1.1
  2438. // but at the time the v1.11 schema API was written we didn't know that so
  2439. // we'll return the version 1.11 so the schema API will work.
  2440. if (strcmp($exact_version, '1.11 or older') == 0) {
  2441. $exact_version = "1.11";
  2442. if ($warn_if_unsupported) {
  2443. drupal_set_message(t("WARNING: Tripal does not fully support Chado version less than v1.11. If you are certain this is v1.11
  2444. or if Chado was installed using an earlier version of Tripal then all is well. If not please upgrade to v1.11 or later"),
  2445. 'warning');
  2446. }
  2447. }
  2448. // if not returing an exact version, return the version to the nearest 10th.
  2449. // return 1.2 for all versions of 1.2x
  2450. $effective_version = $exact_version;
  2451. if (preg_match('/^1\.2\d+$/', $effective_version)) {
  2452. $effective_version = "1.2";
  2453. }
  2454. if ($warn_if_unsupported and ($effective_version != 1.11 and $effective_version != 1.2 and $effective_version != 'not installed')) {
  2455. drupal_set_message(t("WARNING: The currently installed version of Chado, v$exact_version, is not fully compatible with Tripal."), 'warning');
  2456. }
  2457. // if the callee has requested the exact version then return it
  2458. if ($exact) {
  2459. return $exact_version;
  2460. }
  2461. return $effective_version;
  2462. }
  2463. /**
  2464. * Retrieves the chado tables Schema API array.
  2465. *
  2466. * @param $table
  2467. * The name of the table to retrieve. The function will use the appopriate
  2468. * Tripal chado schema API hooks (e.g. v1.11 or v1.2).
  2469. *
  2470. * @returns
  2471. * A Drupal Schema API array defining the table.
  2472. *
  2473. * @ingroup tripal_core_api
  2474. */
  2475. function tripal_core_get_chado_table_schema($table) {
  2476. // first get the chado version that is installed
  2477. $v = tripal_core_get_chado_version();
  2478. // get the table array from the proper chado schema
  2479. $v = preg_replace("/\./", "_", $v); // reformat version for hook name
  2480. $table_arr = module_invoke_all("chado_schema_v" . $v . "_" . $table);
  2481. // if the table_arr is empty then maybe this is a custom table
  2482. if (!is_array($table_arr) or count($table_arr) == 0) {
  2483. $table_arr = tripal_get_chado_custom_schema($table);
  2484. }
  2485. return $table_arr;
  2486. }
  2487. /**
  2488. * This function will delete Drupal nodes for any sync'ed table (e.g.
  2489. * feature, organism, analysis, stock, library) if the chado record has been
  2490. * deleted or the entry in the chado_[table] table has been removed.
  2491. *
  2492. * @param $table
  2493. * The name of the table that corresonds to the node type we want to clean up.
  2494. * @param $job_id
  2495. * This should be the job id from the Tripal jobs system. This function
  2496. * will update the job status using the provided job ID.
  2497. *
  2498. * @ingroup tripal_core_api
  2499. */
  2500. function tripal_core_clean_orphaned_nodes($table, $job_id) {
  2501. $count = 0;
  2502. // build the SQL statments needed to check if nodes point to valid analyses
  2503. $dsql = "SELECT * FROM {node} WHERE type = 'chado_" . $table . "' order by nid";
  2504. $nsql = "SELECT * FROM {node} WHERE nid = :nid";
  2505. $csql = "SELECT * FROM {chado_" . $table . "} WHERE nid = :nid ";
  2506. $clsql= "SELECT * FROM {chado_" . $table . "}";
  2507. $lsql = "SELECT * FROM {" . $table . "} where " . $table . "_id = :" . $table . "_id ";
  2508. // load into nodes array
  2509. print "Getting nodes\n";
  2510. $nodes = array();
  2511. $res = db_query($dsql);
  2512. foreach ($res as $node) {
  2513. $nodes[$count] = $node;
  2514. $count++;
  2515. }
  2516. // load the chado_$table into an array
  2517. print "Getting chado_$table\n";
  2518. $cnodes = array();
  2519. $res = db_query($clsql);
  2520. foreach ($res as $node) {
  2521. $cnodes[$count] = $node;
  2522. $count++;
  2523. }
  2524. $interval = intval($count * 0.01);
  2525. if ($interval < 1) {
  2526. $interval = 1;
  2527. }
  2528. // iterate through all of the chado_$table entries and remove those
  2529. // that don't have a node or don't have a $table record in chado.libary
  2530. print "Verifying all chado_$table Entries\n";
  2531. $deleted = 0;
  2532. foreach ($cnodes as $nid) {
  2533. // update the job status every 1% analyses
  2534. if ($job_id and $i % $interval == 0) {
  2535. tripal_job_set_progress($job_id, intval(($i / $count) * 100));
  2536. }
  2537. // see if the node exits, if not remove the entry from the chado_$table table
  2538. $results = db_query($nsql, array(':nid' => $nid->nid));
  2539. $node = $results->fetchObject();
  2540. if (!$node) {
  2541. $deleted++;
  2542. db_query("DELETE FROM {chado_" . $table . "} WHERE nid = :nid", array(':nid' => $nid->nid));
  2543. $message = "chado_$table missing node.... DELETING: $nid->nid";
  2544. watchdog('tripal_core', $message, array(), WATCHDOG_WARNING);
  2545. }
  2546. // see if the record in chado exist, if not remove the entry from the chado_$table
  2547. $table_id = $table . "_id";
  2548. $results = chado_query($lsql, array(":" . $table . "_id " => $nid->$table_id));
  2549. $record = $results->fetchObject();
  2550. if (!$record) {
  2551. $deleted++;
  2552. $sql = "DELETE FROM {chado_" . $table . "} WHERE " . $table . "_id = :" . $table . "_id";
  2553. db_query($sql, array(":" . $table . "_id" => $nid->$table_id));
  2554. $message = "chado_$table missing $table.... DELETING entry.";
  2555. watchdog('tripal_core', $message, array(), WATCHDOG_WARNING);
  2556. }
  2557. $i++;
  2558. }
  2559. print "\t$deleted chado_$table entries missing either a node or chado entry.\n";
  2560. // iterate through all of the nodes and delete those that don't
  2561. // have a corresponding entry in chado_$table
  2562. $deleted = 0;
  2563. foreach ($nodes as $node) {
  2564. // update the job status every 1% libraries
  2565. if ($job_id and $i % $interval == 0) {
  2566. tripal_job_set_progress($job_id, intval(($i / $count) * 100));
  2567. }
  2568. // check to see if the node has a corresponding entry
  2569. // in the chado_$table table. If not then delete the node.
  2570. $results = db_query($csql, array(":nid" => $node->nid));
  2571. $link = $results->fetchObject();
  2572. if (!$link) {
  2573. if (node_access('delete', $node)) {
  2574. $deleted++;
  2575. $message = "Node missing in chado_$table table.... DELETING node $node->nid";
  2576. watchdog("tripal_core", $message, array(), WATCHDOG_WARNING);
  2577. node_delete($node->nid);
  2578. }
  2579. else {
  2580. $message = "Node missing in chado_$table table.... but cannot delete due to improper permissions (node $node->nid)";
  2581. watchdog("tripal_core", $message, array(), WATCHDOG_WARNING);
  2582. }
  2583. }
  2584. $i++;
  2585. }
  2586. print "\t$deleted nodes did not have corresponding chado_$table entries.\n";
  2587. return '';
  2588. }
  2589. /**
  2590. * Check whether chado is installed (either in the same or a different database)
  2591. *
  2592. * @return
  2593. * TRUE/FALSE depending upon whether chado is installed.
  2594. *
  2595. * @ingroup tripal_chado_api
  2596. */
  2597. function tripal_core_is_chado_installed() {
  2598. global $databases;
  2599. // first check if chado is in the $databases variable of the settings.php file
  2600. if (array_key_exists('chado', $databases)) {
  2601. return TRUE;
  2602. }
  2603. // check to make sure the chado schema exists
  2604. return tripal_core_chado_schema_exists();
  2605. }
  2606. /**
  2607. * Check whether chado is installed local to the Drupal database
  2608. * in its own Chado schema.
  2609. *
  2610. * @return
  2611. * TRUE/FALSE depending upon whether chado is local.
  2612. *
  2613. * @ingroup tripal_chado_api
  2614. */
  2615. function tripal_core_is_chado_local() {
  2616. global $db_url, $db_type;
  2617. $is_installed = tripal_core_is_chado_installed();
  2618. if ($is_installed) {
  2619. if (is_array($db_url)) {
  2620. if (isset($db_url['chado'])) {
  2621. return FALSE;
  2622. }
  2623. }
  2624. return TRUE;
  2625. }
  2626. return FALSE;
  2627. }
  2628. /**
  2629. * Determine whether a given chado table is directly linked to a node
  2630. *
  2631. * @param $chado_table
  2632. * The name of a chado table to check (ie: feature)
  2633. * @return
  2634. * TRUE if it is linked to a node and FALSE otherwise
  2635. */
  2636. function tripal_core_is_tripal_node_type($chado_table) {
  2637. $linking_table = 'chado_' . $chado_table;
  2638. if (db_table_exists($linking_table)) {
  2639. return TRUE;
  2640. }
  2641. else {
  2642. return FALSE;
  2643. }
  2644. }
  2645. /**
  2646. * Set the Tripal Database
  2647. *
  2648. * The tripal_db_set_active function is used to prevent namespace collisions
  2649. * when chado and drupal are installed in the same database but in different
  2650. * schemas. It is also used for backwards compatibility with older versions
  2651. * of tripal or in cases where chado is located outside of the Drupal database.
  2652. * or when using Drupal functions such as db_table_exists()
  2653. *
  2654. * @ingroup tripal_chado_api
  2655. */
  2656. function tripal_db_set_active($dbname = 'default') {
  2657. global $databases, $active_db;
  2658. $chado_exists = variable_get('chado_schema_exists', FALSE);
  2659. if ($chado_exists) {
  2660. if ($dbname == 'chado') {
  2661. db_query('set search_path to chado');
  2662. return 'default';
  2663. }
  2664. else {
  2665. db_query('set search_path to public');
  2666. return 'chado';
  2667. }
  2668. }
  2669. // if the 'chado' database is in the $db_url variable then chado is
  2670. // not in the same Drupal database, so we don't need to set any
  2671. // search_path and can just change the database
  2672. elseif (array_key_exists($dbname, $databases)) {
  2673. return db_set_active($dbname);
  2674. }
  2675. }