tripal_core.api.inc 140 KB

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