tripal_core_chado.api.inc 104 KB

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