tripal_core_chado.api.inc 109 KB

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