tripal_core_chado.api.inc 103 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870
  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. $object->{$foreign_table} = $foreign_object;
  1545. $object->expanded = $to_expand;
  1546. }
  1547. }
  1548. // if the object returned is NULL then handle that
  1549. else {
  1550. if (count($foreign_table_desc['foreign keys'][$base_table]['columns']) > 1) {
  1551. $object->{$foreign_table}->{$left} = NULL;
  1552. }
  1553. else {
  1554. $object->{$foreign_table} = NULL;
  1555. }
  1556. }
  1557. }
  1558. }
  1559. // if the foreign table is not connected to the base table through a FK constraint
  1560. else {
  1561. // We need to recurse -the table has a relationship to one of the nested objects
  1562. $did_expansion = 0;
  1563. foreach ((array) $object as $field_name => $field_value) {
  1564. // if we have a nested object ->expand the table in it
  1565. if (is_object($field_value)) {
  1566. $did_expansion = 1;
  1567. $object->{$field_name} = tripal_core_expand_chado_vars($field_value, 'table', $foreign_table);
  1568. }
  1569. }
  1570. // if we did not expand this table we should return a message that the foreign table
  1571. // could not be expanded
  1572. if (!$did_expansion) {
  1573. watchdog('tripal_core', 'tripal_core_expand_chado_vars: Could not expand table, %table. It is ' .
  1574. 'not in a foreign key relationship with the base object nor with any other expanded table. ' .
  1575. 'Check the table definition to ensure that a proper foreign key relationship is present.',
  1576. array('%table' => $foreign_table), WATCHDOG_ERROR);
  1577. }
  1578. }
  1579. break;
  1580. case "node": //---------------------------------------------------------------------------------
  1581. //if the node to be expanded is for our base table, then just expand it
  1582. if ($object->tablename == $to_expand) {
  1583. $node = node_load($object->nid);
  1584. if ($node) {
  1585. $object->expanded = $to_expand;
  1586. $node->expandable_fields = $object->expandable_fields;
  1587. unset($object->expandable_fields);
  1588. $node->expandable_tables = $object->expandable_tables;
  1589. unset($object->expandable_tables);
  1590. $node->expandable_nodes = $object->expandable_nodes;
  1591. unset($object->expandable_nodes);
  1592. $node->{$base_table} = $object;
  1593. $object = $node;
  1594. }
  1595. else {
  1596. watchdog('tripal_core', 'tripal_core_expand_chado_vars: No node matches the nid (%nid) supplied.',
  1597. array('%nid' => $object->nid), WATCHDOG_ERROR);
  1598. } //end of if node
  1599. }
  1600. else {
  1601. //We need to recurse -the node to expand is one of the nested objects
  1602. foreach ((array) $object as $field_name => $field_value) {
  1603. if (is_object($field_value)) {
  1604. $object->{$field_name} = tripal_core_expand_chado_vars(
  1605. $field_value,
  1606. 'node',
  1607. $to_expand
  1608. );
  1609. }
  1610. } //end of for each field in the current object
  1611. }
  1612. break;
  1613. default:
  1614. watchdog('tripal_core', 'tripal_core_expand_chado_vars: Unrecognized type (%type). Should be one of "field", "table", "node".',
  1615. array('%type' => $type), WATCHDOG_ERROR);
  1616. return FALSE;
  1617. }
  1618. //move extended array downwards-------------------------------------------------------------------
  1619. if (!$object->expanded) {
  1620. //if there's no extended field then go hunting for it
  1621. foreach ( (array)$object as $field_name => $field_value) {
  1622. if (is_object($field_value)) {
  1623. if (isset($field_value->expanded)) {
  1624. $object->expanded = $field_value->expanded;
  1625. unset($field_value->expanded);
  1626. }
  1627. }
  1628. }
  1629. }
  1630. //try again becasue now we might have moved it down
  1631. if ($object->expanded) {
  1632. $expandable_name = 'expandable_' . $type . 's';
  1633. if ($object->{$expandable_name}) {
  1634. $key_to_remove = array_search($object->expanded, $object->{$expandable_name});
  1635. unset($object->{$expandable_name}[$key_to_remove]);
  1636. unset($object->expanded);
  1637. }
  1638. else {
  1639. // if there is an expandable array then we've reached the base object
  1640. // if we get here and don't have anything expanded then something went wrong
  1641. // watchdog(
  1642. // 'tripal_core',
  1643. // 'tripal_core_expand_chado_vars: Unable to expand the %type %to_expand',
  1644. // array('%type'=>$type, '%to_expand'=>$to_expand),
  1645. // WATCHDOG_ERROR
  1646. // );
  1647. } //end of it we've reached the base object
  1648. }
  1649. return $object;
  1650. }
  1651. /**
  1652. * Implements hook_exclude_type_by_default()
  1653. *
  1654. * This hooks allows fields of a specified type that match a specified criteria to be excluded by
  1655. * default from any table when tripal_core_generate_chado_var() is called. Keep in mind that if
  1656. * fields are excluded by default they can always be expanded at a later date using
  1657. * tripal_core_expand_chado_vars().
  1658. *
  1659. * Criteria are php strings that evaluate to either TRUE or FALSE. These strings are evaluated using
  1660. * drupal_eval() which suppresses syntax errors and throws watchdog entries of type php. There are
  1661. * also watchdog entries of type tripal_core stating the exact criteria evaluated. Criteria can
  1662. * contain the following tokens:
  1663. * - &gt;field_name&lt;
  1664. * Replaced by the name of the field to be excluded
  1665. * - &gt;field_value&lt;
  1666. * Replaced by the value of the field in the current record
  1667. * Also keep in mind that if your criteria doesn't contain the &gt;field_value&lt; token then it will be
  1668. * evaluated before the query is executed and if the field is excluded it won't be included in the
  1669. * query.
  1670. *
  1671. * @return
  1672. * An array of type => criteria where the type is excluded if the criteria evaluates to TRUE
  1673. *
  1674. * @ingroup tripal_chado_api
  1675. */
  1676. function tripal_core_exclude_type_by_default() {
  1677. return array('text' => 'strlen("&gt;field_value&lt; ") > 100');
  1678. }
  1679. /**
  1680. * Implements hook_exclude_field_from_<tablename>_by_default()
  1681. *
  1682. * This hooks allows fields from a specified table that match a specified criteria to be excluded by
  1683. * default from any table when tripal_core_generate_chado_var() is called. Keep in mind that if
  1684. * fields are excluded by default they can always be expanded at a later date using
  1685. * tripal_core_expand_chado_vars().
  1686. *
  1687. * Criteria are php strings that evaluate to either TRUE or FALSE. These strings are evaluated using
  1688. * drupal_eval() which suppresses syntax errors and throws watchdog entries of type php. There are
  1689. * also watchdog entries of type tripal_core stating the exact criteria evaluated. Criteria can
  1690. * contain the following tokens:
  1691. * - &gt;field_name&lt;
  1692. * Replaced by the name of the field to be excluded
  1693. * - &gt;field_value&lt;
  1694. * Replaced by the value of the field in the current record
  1695. * Also keep in mind that if your criteria doesn't contain the &gt;field_value&lt; token then it will be
  1696. * evaluated before the query is executed and if the field is excluded it won't be included in the
  1697. * query.
  1698. *
  1699. * @return
  1700. * An array of type => criteria where the type is excluded if the criteria evaluates to TRUE
  1701. *
  1702. * @ingroup tripal_chado_api
  1703. */
  1704. function tripal_core_exclude_field_from_feature_by_default() {
  1705. return array();
  1706. }
  1707. /**
  1708. * Use this function instead of pager_query() when selecting a
  1709. * subset of records from a Chado table.
  1710. *
  1711. * @param $query
  1712. * The SQL statement to execute, this is followed by a variable number of args
  1713. * used as substitution values in the SQL statement.
  1714. * @param $limit
  1715. * The number of query results to display per page.
  1716. * @param $element
  1717. * An optional integer to distinguish between multiple pagers on one page.
  1718. * @param $count_query
  1719. * An SQL query used to count matching records.
  1720. *
  1721. * @returns
  1722. * A database query result resource or FALSE if the query was not
  1723. * executed correctly
  1724. *
  1725. * @ingroup tripal_chado_api
  1726. */
  1727. function chado_pager_query($query, $limit, $element, $count_query) {
  1728. // The following code is almost an exact duplicate of the
  1729. // Drupal pager_query function. However, substitions have
  1730. // been made to call chado_query rather than db_query
  1731. global $pager_page_array, $pager_total, $pager_total_items;
  1732. $page = isset($_GET['page']) ? $_GET['page'] : '';
  1733. // get the SQL query arguments that get substituted into modifiers later.
  1734. $args = func_get_args();
  1735. $args = array_slice($args, 4);
  1736. // Alternative syntax for '...'
  1737. if (isset($args[0]) && is_array($args[0])) {
  1738. $args = $args[0];
  1739. }
  1740. // Construct a count query if none was given.
  1741. if (!isset($count_query)) {
  1742. $count_query = preg_replace(array('/SELECT.*?FROM /As', '/ORDER BY .*/'), array('SELECT COUNT(*) FROM ', ''), $query);
  1743. }
  1744. // Convert comma-separated $page to an array, used by other functions.
  1745. $pager_page_array = explode(',', $page);
  1746. // We calculate the total of pages as ceil(items / limit).
  1747. $pager_total_items[$element] = db_result(chado_query($count_query, $args));
  1748. $pager_total[$element] = ceil($pager_total_items[$element] / $limit);
  1749. $pager_page_array[$element] = max(0, min((int) $pager_page_array[$element], ((int) $pager_total[$element]) - 1));
  1750. return chado_query_range($query, $args, $pager_page_array[$element] * $limit, $limit);
  1751. }
  1752. /**
  1753. * Use this function instead of db_query_range().
  1754. *
  1755. * @param $sql
  1756. * The SQL statement to execute, this is followed by a variable number of args
  1757. * used as substitution values in the SQL statement.
  1758. * @param $args
  1759. * The SQL arguments
  1760. * @param $from
  1761. * The first result row to return..
  1762. * @param $count
  1763. * The maximum number of result rows to return.
  1764. *
  1765. * @returns
  1766. * A database query result resource or FALSE if the query was not
  1767. * executed correctly
  1768. *
  1769. * @ingroup tripal_chado_api
  1770. */
  1771. function chado_query_range($query, $args, $from, $count) {
  1772. $query .= ' LIMIT ' . (int) $count . ' OFFSET ' . (int) $from;
  1773. return chado_query($query, $args);
  1774. }
  1775. /**
  1776. * Use this function instead of db_query() to avoid switching databases
  1777. * when making query to the chado database
  1778. *
  1779. * Will use a chado persistent connection if it already exists
  1780. *
  1781. * @param $sql
  1782. * The sql statement to execute
  1783. *
  1784. * @param $args
  1785. * The array of arguments, with the same structure as passed to
  1786. * the db_query() function of Drupal.
  1787. *
  1788. * @return
  1789. * DatabaseStatementInterface A prepared statement object, already executed.
  1790. *
  1791. * @ingroup tripal_chado_api
  1792. */
  1793. function chado_query($sql, $args = array()) {
  1794. $is_local = tripal_core_is_chado_local();
  1795. // if Chado is local to the database then prefix the Chado table
  1796. // names with 'chado'.
  1797. if ($is_local) {
  1798. $sql = preg_replace('/\n/', '', $sql); // remove carriage returns
  1799. $sql = preg_replace('/\{(.*?)\}/', 'chado.$1', $sql);
  1800. $results = db_query($sql, $args);
  1801. }
  1802. // if Chado is not local to the Drupal database then we have to
  1803. // switch to another database
  1804. else {
  1805. $previous_db = tripal_db_set_active('chado') ;
  1806. $results = db_query($sql);
  1807. tripal_db_set_active($previous_db);
  1808. }
  1809. return $results;
  1810. }
  1811. /**
  1812. * Get chado id for a node. E.g, if you want to get 'analysis_id' from the
  1813. * 'analysis' table for a synced 'chado_analysis' node, (the same for
  1814. * organisms and features):
  1815. * $analysis_id = chado_get_id_for_node ('analysis', $node->nid)
  1816. * $organism_id = chado_get_id_for_node ('organism', $node->nid)
  1817. * $feature_id = chado_get_id_for_node ('feature', $node->nid)
  1818. *
  1819. * @param $table
  1820. * @param $nid
  1821. *
  1822. * @ingroup tripal_chado_api
  1823. */
  1824. function chado_get_id_for_node($table, $nid) {
  1825. $sql = "SELECT " . $table . "_id as id FROM {chado_$table} WHERE nid = :nid";
  1826. $result = db_query($sql, array(':nid' => $nid))->fetchObject();
  1827. return $result->id;
  1828. }
  1829. /**
  1830. * Get node id for a chado feature/organism/analysis. E.g, if you want to
  1831. * get the node id for an analysis, use:
  1832. * $nid = chado_get_node_id ('analysis', $analysis_id)
  1833. * Likewise,
  1834. * $nid = chado_get_node_id ('organism', $organism_id)
  1835. * $nid = chado_get_node_id ('feature', $feature_id)
  1836. *
  1837. * @ingroup tripal_chado_api
  1838. */
  1839. function chado_get_node_id($table, $id) {
  1840. $sql = "SELECT nid FROM {chado_$table} WHERE " . $table . "_id = :" . $table . "_id";
  1841. $result = db_query($sql, array(":" . $table . "_id" => $id))->fetchObject();
  1842. return $results->nid;
  1843. }
  1844. /**
  1845. * Retrieve a property for a given base table record
  1846. *
  1847. * @param $basetable
  1848. * The base table for which the property should be retrieved. Thus to retrieve a property
  1849. * for a feature the basetable=feature and property is retrieved from featureprop
  1850. * @param $record_id
  1851. * The foriegn key field of the base table. This should be in integer.
  1852. * @param $property
  1853. * The cvterm name describing the type of properties to be retrieved
  1854. * @param $cv_name
  1855. * The name of the cv that the above cvterm is part of
  1856. *
  1857. * @return
  1858. * An array in the same format as that generated by the function
  1859. * tripal_core_generate_chado_var(). If only one record is returned it
  1860. * is a single object. If more than one record is returned then it is an array
  1861. * of objects
  1862. *
  1863. * @ingroup tripal_chado_api
  1864. */
  1865. function tripal_core_get_property($basetable, $record_id, $property, $cv_name) {
  1866. // get the foreign key for this property table
  1867. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  1868. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1869. // construct the array of values to be selected
  1870. $values = array(
  1871. $fkcol => $record_id,
  1872. 'type_id' => array(
  1873. 'cv_id' => array(
  1874. 'name' => $cv_name,
  1875. ),
  1876. 'name' => $property,
  1877. 'is_obsolete' => 0
  1878. ),
  1879. );
  1880. $results = tripal_core_generate_chado_var($basetable . 'prop', $values);
  1881. if ($results) {
  1882. $results = tripal_core_expand_chado_vars($results, 'field', $basetable . 'prop.value');
  1883. }
  1884. return $results;
  1885. }
  1886. /**
  1887. * Insert a property for a given base table. By default if the property already
  1888. * exists a new property is added with the next available rank. If
  1889. * $update_if_present argument is specified then the record will be updated if it
  1890. * exists rather than adding a new property.
  1891. *
  1892. * @param $basetable
  1893. * The base table for which the property should be inserted. Thus to insert a property
  1894. * for a feature the basetable=feature and property is inserted into featureprop
  1895. * @param $record_id
  1896. * The foriegn key value of the base table. This should be in integer.
  1897. * @param $property
  1898. * The cvterm name describing the type of properties to be inserted
  1899. * @param $cv_name
  1900. * The name of the cv that the above cvterm is part of
  1901. * @param $value
  1902. * The value of the property to be inserted (can be empty)
  1903. * @param $update_if_present
  1904. * A boolean indicating whether an existing record should be updated. If the
  1905. * property already exists and this value is not specified or is zero then
  1906. * a new property will be added with the next largest rank.
  1907. *
  1908. * @return
  1909. * Return True on Insert/Update and False otherwise
  1910. *
  1911. * @ingroup tripal_chado_api
  1912. */
  1913. function tripal_core_insert_property($basetable, $record_id, $property,
  1914. $cv_name, $value, $update_if_present = 0) {
  1915. // first see if the property already exists, if the user want's to update
  1916. // then we can do that, but otherwise we want to increment the rank and
  1917. // insert
  1918. $props = tripal_core_get_property($basetable, $record_id, $property, $cv_name);
  1919. if (!is_array($props) and $props) {
  1920. $props = array($props);
  1921. }
  1922. $rank = 0;
  1923. if (count($props) > 0) {
  1924. if ($update_if_present) {
  1925. return tripal_core_update_property($basetable, $record_id, $property, $cv_name, $value);
  1926. }
  1927. else {
  1928. // iterate through the properties returned and check to see if the
  1929. // property with this value already exists if not, get the largest rank
  1930. // and insert the same property but with this new value
  1931. foreach ($props as $p) {
  1932. if ($p->rank > $rank) {
  1933. $rank = $p->rank;
  1934. }
  1935. if (strcmp($p->value, $value) == 0) {
  1936. return TRUE;
  1937. }
  1938. }
  1939. // now add 1 to the rank
  1940. $rank++;
  1941. }
  1942. }
  1943. // make sure the cvterm exists. Otherwise we'll get an error with
  1944. // prepared statements not matching
  1945. $values = array(
  1946. 'cv_id' => array(
  1947. 'name' => $cv_name,
  1948. ),
  1949. 'name' => $property,
  1950. );
  1951. $options = array('statement_name' => 'sel_cvterm_cv');
  1952. $term = tripal_core_chado_select('cvterm', array('cvterm_id'), $values, $options);
  1953. if (!$term or count($term) == 0) {
  1954. watchdog('tripal_core', "Cannot find property '%prop_name'.",
  1955. array('%prop_name' => $property), WATCHDOG_ERROR);
  1956. return FALSE;
  1957. }
  1958. // get the foreign key for this property table
  1959. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  1960. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  1961. // construct the array of values to be inserted
  1962. $values = array(
  1963. $fkcol => $record_id,
  1964. 'type_id' => array(
  1965. 'cv_id' => array(
  1966. 'name' => $cv_name,
  1967. ),
  1968. 'name' => $property,
  1969. ),
  1970. 'value' => $value,
  1971. 'rank' => $rank,
  1972. );
  1973. $options = array('statement_name' => 'ins_' . $basetable . 'prop_' . substr($fkcol, 0, 2) . 'tyvara');
  1974. $result = tripal_core_chado_insert($basetable . 'prop', $values, $options);
  1975. return $result;
  1976. }
  1977. /**
  1978. * Update a property for a given base table record and property name. This
  1979. * function should be used only if one record of the property will be present.
  1980. * If the property name can have multiple entries (with increasing rank) then
  1981. * use the function named tripal_core_update_property_by_id
  1982. *
  1983. * @param $basetable
  1984. * The base table for which the property should be updated. The property table
  1985. * is constructed using a combination of the base table name and the suffix
  1986. * 'prop' (e.g. basetable = feature then property tabie is featureprop).
  1987. * @param $record_id
  1988. * The foreign key of the basetable to update a property for. This should be in integer.
  1989. * For example, if the basetable is 'feature' then the $record_id should be the feature_id
  1990. * @param $property
  1991. * The cvterm name of property to be updated
  1992. * @param $cv_name
  1993. * The name of the cv that the above cvterm is part of
  1994. * @param $value
  1995. * The value of the property to be inserted (can be empty)
  1996. * @param $insert_if_missing
  1997. * A boolean indicating whether a record should be inserted if one doesn't exist to update
  1998. *
  1999. * Note: The property to be updated is select via the unique combination of $record_id and
  2000. * $property and then it is updated with the supplied value
  2001. *
  2002. * @return
  2003. * Return True on Update/Insert and False otherwise
  2004. *
  2005. * @ingroup tripal_chado_api
  2006. */
  2007. function tripal_core_update_property($basetable, $record_id, $property,
  2008. $cv_name, $value, $insert_if_missing = 0) {
  2009. // first see if the property is missing (we can't update a missing property
  2010. $prop = tripal_core_get_property($basetable, $record_id, $property, $cv_name);
  2011. if (count($prop)==0) {
  2012. if ($insert_if_missing) {
  2013. return tripal_core_insert_property($basetable, $record_id, $property, $cv_name, $value);
  2014. }
  2015. else {
  2016. return FALSE;
  2017. }
  2018. }
  2019. // get the foreign key for this property table
  2020. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  2021. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  2022. // construct the array that will match the exact record to update
  2023. $match = array(
  2024. $fkcol => $record_id,
  2025. 'type_id' => array(
  2026. 'cv_id' => array(
  2027. 'name' => $cv_name,
  2028. ),
  2029. 'name' => $property,
  2030. ),
  2031. );
  2032. // construct the array of values to be updated
  2033. $values = array(
  2034. 'value' => $value,
  2035. );
  2036. return tripal_core_chado_update($basetable . 'prop', $match, $values);
  2037. }
  2038. /**
  2039. * Update a property for a given base table record. This function should be
  2040. * used if multiple records of the same property will be present. Also, use this
  2041. * function to change the property name of an existing property.
  2042. *
  2043. * @param $basetable
  2044. * The base table for which the property should be updated. The property table
  2045. * is constructed using a combination of the base table name and the suffix
  2046. * 'prop' (e.g. basetable = feature then property tabie is featureprop).
  2047. * @param $record_id
  2048. * The primary key of the base table. This should be in integer.
  2049. * For example, if the basetable is 'feature' then the $record_id should be the featureprop_id
  2050. * @param $property
  2051. * The cvterm name of property to be updated
  2052. * @param $cv_name
  2053. * The name of the cv that the above cvterm is part of
  2054. * @param $value
  2055. * The value of the property to be inserted (can be empty)
  2056. *
  2057. * @return
  2058. * Return True on Update/Insert and False otherwise
  2059. *
  2060. * @ingroup tripal_chado_api
  2061. */
  2062. function tripal_core_update_property_by_id($basetable, $record_id, $property,
  2063. $cv_name, $value) {
  2064. // get the primary key for this property table
  2065. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  2066. $pkcol = $table_desc['primary key'][0];
  2067. // construct the array that will match the exact record to update
  2068. $match = array(
  2069. $pkcol => $record_id,
  2070. );
  2071. // construct the array of values to be updated
  2072. $values = array(
  2073. 'type_id' => array(
  2074. 'cv_id' => array(
  2075. 'name' => $cv_name,
  2076. ),
  2077. 'name' => $property,
  2078. ),
  2079. 'value' => $value,
  2080. );
  2081. return tripal_core_chado_update($basetable . 'prop', $match, $values);
  2082. }
  2083. /**
  2084. * Deletes a property for a given base table record using the property name
  2085. *
  2086. * @param $basetable
  2087. * The base table for which the property should be deleted. Thus to deleted a property
  2088. * for a feature the basetable=feature and property is deleted from featureprop
  2089. * @param $record_id
  2090. * The primary key of the basetable to delete a property for. This should be in integer.
  2091. * @param $property
  2092. * The cvterm name describing the type of property to be deleted
  2093. * @param $cv_name
  2094. * The name of the cv that the above cvterm is part of
  2095. *
  2096. * Note: The property to be deleted is select via the unique combination of $record_id and $property
  2097. *
  2098. * @return
  2099. * Return True on Delete and False otherwise
  2100. *
  2101. * @ingroup tripal_chado_api
  2102. */
  2103. function tripal_core_delete_property($basetable, $record_id, $property, $cv_name) {
  2104. // get the foreign key for this property table
  2105. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  2106. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  2107. // construct the array that will match the exact record to update
  2108. $match = array(
  2109. $fkcol => $record_id,
  2110. 'type_id' => array(
  2111. 'cv_id' => array(
  2112. 'name' => $cv_name,
  2113. ),
  2114. 'name' => $property,
  2115. ),
  2116. );
  2117. return tripal_core_chado_delete($basetable . 'prop', $match);
  2118. }
  2119. /**
  2120. * Deletes a property using the property ID
  2121. *
  2122. * @param $basetable
  2123. * The base table for which the property should be deleted. Thus to deleted a property
  2124. * for a feature the basetable=feature and property is deleted from featureprop
  2125. * @param $record_id
  2126. * The primary key of the basetable to delete a property for. This should be in integer.
  2127. *
  2128. * @return
  2129. * Return True on Delete and False otherwise
  2130. *
  2131. * @ingroup tripal_chado_api
  2132. */
  2133. function tripal_core_delete_property_by_id($basetable, $record_id) {
  2134. // get the foreign key for this property table
  2135. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  2136. $pkcol = $table_desc['primary key'][0];
  2137. // construct the array that will match the exact record to update
  2138. $match = array(
  2139. $pkcol => $record_id,
  2140. );
  2141. return tripal_core_chado_delete($basetable . 'prop', $match);
  2142. }
  2143. /**
  2144. * Start a transaction block. Ensures the use of a persistent chado connection
  2145. */
  2146. function tripal_db_start_transaction() {
  2147. /* $connection = tripal_db_persistent_chado();
  2148. if ($connection) {
  2149. chado_query("BEGIN");
  2150. return $connection;
  2151. }
  2152. return FALSE;
  2153. */
  2154. }
  2155. /**
  2156. * Set a savepoint to roll the current transaction back to if an error is encountered
  2157. */
  2158. function tripal_db_set_savepoint_transaction($savepoint, $release = FALSE) {
  2159. // Postgresql requires a savepoint of the same name to be unset before re-use
  2160. if ($release) {
  2161. chado_query("RELEASE SAVEPOINT :savepoint", array(':savepoint' => $savepoint));
  2162. }
  2163. chado_query("SAVEPOINT :savepoint", array(':savepoint' => $savepoint));
  2164. }
  2165. /**
  2166. * A simple function to commit a database transaction
  2167. *
  2168. * @return nothing
  2169. */
  2170. function tripal_db_commit_transaction() {
  2171. chado_query("COMMIT");
  2172. }
  2173. /**
  2174. * Rollback changes.
  2175. *
  2176. * If $savepoint is NULL then rollback to the beginning of the transaction,
  2177. * Otherwise, rollback to the point at which the named $savepoint was created
  2178. *
  2179. * @param $savepoint
  2180. * The name of the saved point in the transaction to rollback to
  2181. *
  2182. * @param $commit
  2183. * The transcation will only be committed if this value is TRUE. The
  2184. * default is TRUE.
  2185. *
  2186. * @return nothing
  2187. */
  2188. function tripal_db_rollback_transaction($savepoint = NULL, $commit = TRUE) {
  2189. if ($savepoint) {
  2190. chado_query("ROLLBACK TO SAVEPOINT :savepoint", array(':savepoint' => $savepoint));
  2191. }
  2192. else {
  2193. chado_query("ROLLBACK");
  2194. }
  2195. if ($commit) {
  2196. tripal_db_commit_transaction();
  2197. }
  2198. }
  2199. /**
  2200. * Retrieves the schema in an array for the specified custom table.
  2201. *
  2202. * @param $table
  2203. * The name of the table to create.
  2204. *
  2205. * @return
  2206. * A Drupal-style Schema API array definition of the table. Returns
  2207. * FALSE on failure.
  2208. *
  2209. * @ingroup tripal_core_api
  2210. */
  2211. function tripal_get_chado_custom_schema($table) {
  2212. $sql = "SELECT schema FROM {tripal_custom_tables} WHERE table_name = :table_name";
  2213. $results = db_query($sql, array(':table_name' => $table));
  2214. $custom = $results->fetchObject();
  2215. if (!$custom) {
  2216. return FALSE;
  2217. }
  2218. else {
  2219. return unserialize($custom->schema);
  2220. }
  2221. }
  2222. /**
  2223. * Check that any given Chado table exists. This function
  2224. * is necessary because Drupa's db_table_exists function
  2225. * hardcodes the 'public'
  2226. *
  2227. * @return
  2228. * TRUE/FALSE depending upon whether it exists
  2229. */
  2230. function chado_table_exists($table) {
  2231. global $databases;
  2232. $default_db = $databases['default']['default']['database'];
  2233. $sql = "
  2234. SELECT 1
  2235. FROM information_schema.tables
  2236. WHERE
  2237. table_name = :table_name AND
  2238. table_schema = 'chado' AND
  2239. table_catalog = '$default_db'
  2240. ";
  2241. $results = db_query($sql, array(':table_name' => $table));
  2242. $exists = $results->fetchObject();
  2243. if (!$exists) {
  2244. return FALSE;
  2245. }
  2246. return TRUE;
  2247. }
  2248. /**
  2249. * Check that the Chado schema exists within the local database
  2250. *
  2251. * @return
  2252. * TRUE/FALSE depending upon whether it exists
  2253. */
  2254. function tripal_core_chado_schema_exists() {
  2255. $exists = variable_get('chado_schema_exists', FALSE);
  2256. if (!$exists) {
  2257. // This is postgresql-specific code to check the existence of the chado schema
  2258. // @coder-ignore: acting on pg_catalog schema rather then drupal schema therefore, table prefixing does not apply
  2259. $sql = "
  2260. SELECT nspname
  2261. FROM pg_catalog.pg_namespace
  2262. WHERE nspname = 'chado'
  2263. ";
  2264. $results = db_query($sql);
  2265. $name = $results->fetchObject();
  2266. if ($name) {
  2267. variable_set('chado_schema_exists', TRUE);
  2268. return TRUE;
  2269. }
  2270. else {
  2271. return FALSE;
  2272. }
  2273. }
  2274. return TRUE;
  2275. }
  2276. /**
  2277. * Check that any given schema exists
  2278. *
  2279. * @param $schema
  2280. * The name of the schema to check the existence of
  2281. *
  2282. * @return
  2283. * TRUE/FALSE depending upon whether or not the schema exists
  2284. *
  2285. * @ingroup tripal_chado_api
  2286. */
  2287. function tripal_core_schema_exists($schema) {
  2288. // check that the chado schema now exists
  2289. $sql = "
  2290. SELECT nspname
  2291. FROM pg_namespace
  2292. WHERE
  2293. has_schema_privilege(nspname, 'USAGE') AND
  2294. nspname = :nspname
  2295. ORDER BY nspname
  2296. ";
  2297. $results = db_query($sql, array(':nspname' => $schema));
  2298. $name = $results->fetchObject();
  2299. if (strcmp($name->nspname, $schema) != 0) {
  2300. return FALSE;
  2301. }
  2302. return TRUE;
  2303. }
  2304. /**
  2305. * Retrieves the list tables in the Chado schema. By default it only retursn
  2306. * the default Chado tables, but may also return custom tables added to the
  2307. * Chado schema as well.
  2308. *
  2309. * @param $include_custom
  2310. * Optional. Set as TRUE to include any custom tables created in the
  2311. * Chado schema. Custom tables are added to Chado using the
  2312. * tripal_core_chado_create_table() function.
  2313. *
  2314. * @returns
  2315. * An associative array where the key and value pairs are the Chado table names.
  2316. *
  2317. * @ingroup tripal_core_api
  2318. */
  2319. function tripal_core_get_chado_tables($include_custom = NULL) {
  2320. // first get the chado version that is installed
  2321. $v = tripal_core_get_chado_version();
  2322. $tables = array();
  2323. if ($v == '1.2') {
  2324. $tables_v1_2 = tripal_core_chado_get_v1_2_tables();
  2325. foreach ($tables_v1_2 as $table) {
  2326. $tables[$table] = $table;
  2327. }
  2328. }
  2329. if ($v == '1.11' or $v == '1.11 or older') {
  2330. $tables_v1_11 = tripal_core_chado_get_v1_11_tables();
  2331. foreach ($tables_v1_11 as $table) {
  2332. $tables[$table] = $table;
  2333. }
  2334. }
  2335. // now add in the custom tables too if requested
  2336. if ($include_custom) {
  2337. $sql = "SELECT table_name FROM {tripal_custom_tables}";
  2338. $resource = db_query($sql);
  2339. foreach ($resource as $r) {
  2340. $tables[$r->table_name] = $r->table_name;
  2341. }
  2342. }
  2343. asort($tables);
  2344. return $tables;
  2345. }
  2346. /**
  2347. * Sets a Drupal variable with the current version of Chado. This variable
  2348. * can then be queried later using the tripal_core_get_chado_Version
  2349. *
  2350. * @returns
  2351. * The version of Chado
  2352. *
  2353. * @ingroup tripal_core_api
  2354. */
  2355. function tripal_core_set_chado_version() {
  2356. global $databases;
  2357. $is_local = 0;
  2358. // check that Chado is installed if not return 'uninstalled as the version'
  2359. $chado_exists = tripal_core_chado_schema_exists();
  2360. if (!$chado_exists) {
  2361. // if it's not in the drupal database check to see if it's specified in the $db_url
  2362. // in the settings.php
  2363. if (!array_key_exists('chado', $databases)) {
  2364. // if it's not in the drupal database or specified in the $db_url then
  2365. // return uninstalled as the version
  2366. return 'not installed';
  2367. }
  2368. $previous_db = tripal_db_set_active('chado');
  2369. $prop_exists = db_table_exists('chadoprop');
  2370. tripal_db_set_active($previous_db);
  2371. }
  2372. else {
  2373. $is_local = 1;
  2374. $prop_exists = db_table_exists('chado.chadoprop');
  2375. }
  2376. // if the table doesn't exist then we don't know what version but we know
  2377. // it must be 1.11 or older.
  2378. if (!$prop_exists) {
  2379. return "1.11 or older";
  2380. }
  2381. $sql = "
  2382. SELECT value
  2383. FROM {chadoprop} CP
  2384. INNER JOIN {cvterm} CVT on CVT.cvterm_id = CP.type_id
  2385. INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
  2386. WHERE CV.name = 'chado_properties' and CVT.name = 'version'
  2387. ";
  2388. if (!$is_local) {
  2389. $previous_db = tripal_db_set_active('chado');
  2390. $results = db_query($sql);
  2391. tripal_db_set_active($previous_db);
  2392. }
  2393. else {
  2394. $results = chado_query($sql);
  2395. }
  2396. $v = $results->fetchObject();
  2397. // if we don't have a version in the chadoprop table then it must be
  2398. // v1.11 or older
  2399. if (!$v) {
  2400. variable_set('chado_version', "1.11 or older");
  2401. return "1.11 or older";
  2402. }
  2403. variable_set('chado_version', $v->value);
  2404. return $v->value;
  2405. }
  2406. /**
  2407. * Returns the version number of the currently installed Chado instance.
  2408. * It can return the real or effective version.
  2409. *
  2410. * @param $exact
  2411. * Set this argument to 1 to retrieve the exact version that is installed.
  2412. * Otherwise, this function will set the version to the nearest 'tenth'.
  2413. * Chado versioning numbers in the hundreds represent changes to the
  2414. * software and not the schema. Changes in the tenth's represent changes
  2415. * in the schema.
  2416. *
  2417. * @param $warn_if_unsupported
  2418. * If the currently installed version of Chado is not supported by Tripal
  2419. * the generatea a Drupal warning.
  2420. *
  2421. * @returns
  2422. * The version of Chado
  2423. *
  2424. * @ingroup tripal_core_api
  2425. */
  2426. function tripal_core_get_chado_version($exact = FALSE, $warn_if_unsupported = FALSE) {
  2427. // first get the chado version that is installed
  2428. $exact_version = variable_get('chado_version', '');
  2429. if (!$exact_version) {
  2430. $exact_version = tripal_core_set_chado_version();
  2431. }
  2432. // Tripal only supports v1.11 or newer.. really this is the same as v1.1
  2433. // but at the time the v1.11 schema API was written we didn't know that so
  2434. // we'll return the version 1.11 so the schema API will work.
  2435. if (strcmp($exact_version, '1.11 or older') == 0) {
  2436. $exact_version = "1.11";
  2437. if ($warn_if_unsupported) {
  2438. drupal_set_message(t("WARNING: Tripal does not fully support Chado version less than v1.11. If you are certain this is v1.11
  2439. or if Chado was installed using an earlier version of Tripal then all is well. If not please upgrade to v1.11 or later"),
  2440. 'warning');
  2441. }
  2442. }
  2443. // if not returing an exact version, return the version to the nearest 10th.
  2444. // return 1.2 for all versions of 1.2x
  2445. $effective_version = $exact_version;
  2446. if (preg_match('/^1\.2\d+$/', $effective_version)) {
  2447. $effective_version = "1.2";
  2448. }
  2449. if ($warn_if_unsupported and ($effective_version != 1.11 and $effective_version != 1.2 and $effective_version != 'not installed')) {
  2450. drupal_set_message(t("WARNING: The currently installed version of Chado, v$exact_version, is not fully compatible with Tripal."), 'warning');
  2451. }
  2452. // if the callee has requested the exact version then return it
  2453. if ($exact) {
  2454. return $exact_version;
  2455. }
  2456. return $effective_version;
  2457. }
  2458. /**
  2459. * Retrieves the chado tables Schema API array.
  2460. *
  2461. * @param $table
  2462. * The name of the table to retrieve. The function will use the appopriate
  2463. * Tripal chado schema API hooks (e.g. v1.11 or v1.2).
  2464. *
  2465. * @returns
  2466. * A Drupal Schema API array defining the table.
  2467. *
  2468. * @ingroup tripal_core_api
  2469. */
  2470. function tripal_core_get_chado_table_schema($table) {
  2471. // first get the chado version that is installed
  2472. $v = tripal_core_get_chado_version();
  2473. // get the table array from the proper chado schema
  2474. $v = preg_replace("/\./", "_", $v); // reformat version for hook name
  2475. $table_arr = module_invoke_all("chado_schema_v" . $v . "_" . $table);
  2476. // if the table_arr is empty then maybe this is a custom table
  2477. if (!is_array($table_arr) or count($table_arr) == 0) {
  2478. $table_arr = tripal_get_chado_custom_schema($table);
  2479. }
  2480. return $table_arr;
  2481. }
  2482. /**
  2483. * This function will delete Drupal nodes for any sync'ed table (e.g.
  2484. * feature, organism, analysis, stock, library) if the chado record has been
  2485. * deleted or the entry in the chado_[table] table has been removed.
  2486. *
  2487. * @param $table
  2488. * The name of the table that corresonds to the node type we want to clean up.
  2489. * @param $job_id
  2490. * This should be the job id from the Tripal jobs system. This function
  2491. * will update the job status using the provided job ID.
  2492. *
  2493. * @ingroup tripal_core_api
  2494. */
  2495. function tripal_core_clean_orphaned_nodes($table, $job_id) {
  2496. $count = 0;
  2497. // build the SQL statments needed to check if nodes point to valid analyses
  2498. $dsql = "SELECT * FROM {node} WHERE type = 'chado_" . $table . "' order by nid";
  2499. $nsql = "SELECT * FROM {node} WHERE nid = :nid";
  2500. $csql = "SELECT * FROM {chado_" . $table . "} WHERE nid = :nid ";
  2501. $clsql= "SELECT * FROM {chado_" . $table . "}";
  2502. $lsql = "SELECT * FROM {" . $table . "} where " . $table . "_id = :" . $table . "_id ";
  2503. // load into nodes array
  2504. print "Getting nodes\n";
  2505. $nodes = array();
  2506. $res = db_query($dsql);
  2507. foreach ($res as $node) {
  2508. $nodes[$count] = $node;
  2509. $count++;
  2510. }
  2511. // load the chado_$table into an array
  2512. print "Getting chado_$table\n";
  2513. $cnodes = array();
  2514. $res = db_query($clsql);
  2515. foreach ($res as $node) {
  2516. $cnodes[$count] = $node;
  2517. $count++;
  2518. }
  2519. $interval = intval($count * 0.01);
  2520. if ($interval < 1) {
  2521. $interval = 1;
  2522. }
  2523. // iterate through all of the chado_$table entries and remove those
  2524. // that don't have a node or don't have a $table record in chado.libary
  2525. print "Verifying all chado_$table Entries\n";
  2526. $deleted = 0;
  2527. foreach ($cnodes as $nid) {
  2528. // update the job status every 1% analyses
  2529. if ($job_id and $i % $interval == 0) {
  2530. tripal_job_set_progress($job_id, intval(($i / $count) * 100));
  2531. }
  2532. // see if the node exits, if not remove the entry from the chado_$table table
  2533. $results = db_query($nsql, array(':nid' => $nid->nid));
  2534. $node = $results->fetchObject();
  2535. if (!$node) {
  2536. $deleted++;
  2537. db_query("DELETE FROM {chado_" . $table . "} WHERE nid = :nid", array(':nid' => $nid->nid));
  2538. $message = "chado_$table missing node.... DELETING: $nid->nid";
  2539. watchdog('tripal_core', $message, array(), WATCHDOG_WARNING);
  2540. }
  2541. // see if the record in chado exist, if not remove the entry from the chado_$table
  2542. $table_id = $table . "_id";
  2543. $results = chado_query($lsql, array(":" . $table . "_id " => $nid->$table_id));
  2544. $record = $results->fetchObject();
  2545. if (!$record) {
  2546. $deleted++;
  2547. $sql = "DELETE FROM {chado_" . $table . "} WHERE " . $table . "_id = :" . $table . "_id";
  2548. db_query($sql, array(":" . $table . "_id" => $nid->$table_id));
  2549. $message = "chado_$table missing $table.... DELETING entry.";
  2550. watchdog('tripal_core', $message, array(), WATCHDOG_WARNING);
  2551. }
  2552. $i++;
  2553. }
  2554. print "\t$deleted chado_$table entries missing either a node or chado entry.\n";
  2555. // iterate through all of the nodes and delete those that don't
  2556. // have a corresponding entry in chado_$table
  2557. $deleted = 0;
  2558. foreach ($nodes as $node) {
  2559. // update the job status every 1% libraries
  2560. if ($job_id and $i % $interval == 0) {
  2561. tripal_job_set_progress($job_id, intval(($i / $count) * 100));
  2562. }
  2563. // check to see if the node has a corresponding entry
  2564. // in the chado_$table table. If not then delete the node.
  2565. $results = db_query($csql, array(":nid" => $node->nid));
  2566. $link = $results->fetchObject();
  2567. if (!$link) {
  2568. if (node_access('delete', $node)) {
  2569. $deleted++;
  2570. $message = "Node missing in chado_$table table.... DELETING node $node->nid";
  2571. watchdog("tripal_core", $message, array(), WATCHDOG_WARNING);
  2572. node_delete($node->nid);
  2573. }
  2574. else {
  2575. $message = "Node missing in chado_$table table.... but cannot delete due to improper permissions (node $node->nid)";
  2576. watchdog("tripal_core", $message, array(), WATCHDOG_WARNING);
  2577. }
  2578. }
  2579. $i++;
  2580. }
  2581. print "\t$deleted nodes did not have corresponding chado_$table entries.\n";
  2582. return '';
  2583. }
  2584. /**
  2585. * Check whether chado is installed (either in the same or a different database)
  2586. *
  2587. * @return
  2588. * TRUE/FALSE depending upon whether chado is installed.
  2589. *
  2590. * @ingroup tripal_chado_api
  2591. */
  2592. function tripal_core_is_chado_installed() {
  2593. global $databases;
  2594. // first check if chado is in the $databases variable of the settings.php file
  2595. if (array_key_exists('chado', $databases)) {
  2596. return TRUE;
  2597. }
  2598. // check to make sure the chado schema exists
  2599. return tripal_core_chado_schema_exists();
  2600. }
  2601. /**
  2602. * Check whether chado is installed local to the Drupal database
  2603. * in its own Chado schema.
  2604. *
  2605. * @return
  2606. * TRUE/FALSE depending upon whether chado is local.
  2607. *
  2608. * @ingroup tripal_chado_api
  2609. */
  2610. function tripal_core_is_chado_local() {
  2611. global $db_url, $db_type;
  2612. $is_installed = tripal_core_is_chado_installed();
  2613. if ($is_installed) {
  2614. if (is_array($db_url)) {
  2615. if (isset($db_url['chado'])) {
  2616. return FALSE;
  2617. }
  2618. }
  2619. return TRUE;
  2620. }
  2621. return FALSE;
  2622. }
  2623. /**
  2624. * Determine whether a given chado table is directly linked to a node
  2625. *
  2626. * @param $chado_table
  2627. * The name of a chado table to check (ie: feature)
  2628. * @return
  2629. * TRUE if it is linked to a node and FALSE otherwise
  2630. */
  2631. function tripal_core_is_tripal_node_type($chado_table) {
  2632. $linking_table = 'chado_' . $chado_table;
  2633. if (db_table_exists($linking_table)) {
  2634. return TRUE;
  2635. }
  2636. else {
  2637. return FALSE;
  2638. }
  2639. }
  2640. /**
  2641. * Set the Tripal Database
  2642. *
  2643. * The tripal_db_set_active function is used to prevent namespace collisions
  2644. * when chado and drupal are installed in the same database but in different
  2645. * schemas. It is also used for backwards compatibility with older versions
  2646. * of tripal or in cases where chado is located outside of the Drupal database.
  2647. * or when using Drupal functions such as db_table_exists()
  2648. *
  2649. * @ingroup tripal_chado_api
  2650. */
  2651. function tripal_db_set_active($dbname = 'default') {
  2652. global $databases, $active_db;
  2653. $chado_exists = variable_get('chado_schema_exists', FALSE);
  2654. if ($chado_exists) {
  2655. if ($dbname == 'chado') {
  2656. db_query('set search_path to chado');
  2657. return 'default';
  2658. }
  2659. else {
  2660. db_query('set search_path to public');
  2661. return 'chado';
  2662. }
  2663. }
  2664. // if the 'chado' database is in the $db_url variable then chado is
  2665. // not in the same Drupal database, so we don't need to set any
  2666. // search_path and can just change the database
  2667. elseif (array_key_exists($dbname, $databases)) {
  2668. return db_set_active($dbname);
  2669. }
  2670. }