tripal_core_chado.api.inc 138 KB

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